在一個應用程序中,我使用不可編輯的JEditorPanes作爲一種通用的UI小部件,它可以顯示一些複雜的內容(HTML會做到這一點),包裝文本行並捕獲鼠標點擊。不確定JEditorPane是否是一個很好的選擇,所以請隨時提出替代方案。在JScrollPane中的JEditorPane中包裝HTML文本
下面的示例代碼工作得相當好:
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,請指出:)
非常好!我最終創建了一個更簡單,不太靈活的JPanel + Scrollable實現來滿足我自己的需求,它的功能就像一個魅力。 – mjomble 2011-03-03 10:05:26