アプリケーションでは、編集不可能な JEditorPanes を一種の汎用 UI ウィジェットとして使用しています。これは、やや複雑なコンテンツ (HTML でうまくいきます) を表示し、テキスト行を折り返し、マウス クリックをキャッチできます。JEditorPane がこれに適しているかどうかわからないので、代替案を自由に提案してください。
次のサンプル コードはかなりうまく機能します。
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
public class Main {
private static JPanel createPanel() {
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
for (int i = 0; i < 3; i++) {
JEditorPane editorPane = new JEditorPane();
editorPane.setEditable(false);
editorPane.setContentType("text/html");
String text =
"This is <b>item #" + i + "</b>." +
" It's got text on it that should be wrapped."
;
editorPane.setText(text);
GridBagConstraints constraints = new GridBagConstraints();
constraints.gridx = 0;
constraints.gridy = i;
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.weightx = 1.0;
constraints.insets.bottom = 5;
panel.add(editorPane, constraints);
}
return panel;
}
public static void main(String[] args) {
JPanel panel = createPanel();
JFrame frame = new JFrame();
frame.setSize(200, 200);
frame.setLocation(200, 200);
// Change this to switch between examples
boolean useScrollPane = false;
if (useScrollPane) {
JScrollPane scrollPane = new JScrollPane();
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setViewportView(panel);
frame.add(scrollPane);
}
else {
frame.add(panel);
}
frame.setVisible(true);
}
}
そして、以下を生成します。
ただし、これらが多数ある場合は、垂直スクロールバーを使用できます。
そこで、すべてを JScrollPane に入れました (このバージョンを表示するには、サンプル コードでuseScrollPane
変数をに変更します)。true
これにより、ウィンドウの高さを縮小すると垂直スクロールバーが表示されますが、問題はテキストが折り返されなくなったことです。
問題は、テキストの折り返しと垂直スクロールバーの両方を取得するにはどうすればよいかということです。
ご覧のとおり、水平スクロールバーを無効にしましたが、あまり役に立ちませんでした。
PS。私は Swing の経験があまりないので、このコードで初心者向けの WTF を見つけたら、指摘してください :)