5
我有一個JEditorPane
,它顯示在彈出窗口中,通過按鈕觸發。所述面板包含長的文字,因此它嵌套在JScrollPane
內部,並且在彈出被約束爲300×100的最大尺寸:用長文本控制JEditorPane的首選大小
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
String text = "Potentially looooooong text. " +
"Lorem ipsum dolor sit amet, consectetuer" +
"adipiscing elit, sed diam nonummy nibh euismod " +
"tincidunt ut laoreet dolore magna aliquam" +
"adipiscing elit, sed diam nonummy nibh euismod" +
"erat volutpat. Ut wisi enim ad minim veniam, " +
"quis nostrud exerci tation.";
final JEditorPane editorPane = new JEditorPane("text/html", text);
editorPane.setEditable(false);
final JButton button = new JButton("Trigger Popup");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JPopupMenu popup = new JPopupMenu();
popup.setLayout(new BorderLayout());
popup.add(new JScrollPane(editorPane));
Dimension d = popup.getPreferredSize();
int w = Math.min(300, d.width);
int h = Math.min(100, d.height);
popup.setPopupSize(w, h);
Dimension s = button.getSize();
popup.show(button, s.width/2, s.height/2);
}
});
JFrame f = new JFrame("Layout Demo");
f.setSize(200, 200);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLocationRelativeTo(null);
f.getContentPane().add(button);
f.setVisible(true);
}
});
}
當示出了用於第一次JEditorPane
實例(即,當按鈕點擊一次),它在某種程度上似乎上報首選高度太小(1):
後續按鈕點擊之後,佈局只是一個如何指望它(2):
我怎麼能強制執行/施以適當的首選尺寸,因此將總是初始化像(2)?
@finnw:優秀的解釋和變通 - 非常感謝你! – netzwerg 2010-02-08 13:11:00
優秀的解決方案,+1!雖然已經有一段時間了,但我還有一個很好的問題,我嘗試了與JTextPane相同的方法,它不過是一個JEditorPane子類,我正努力深入(BasicTextUI)以瞭解它們之間的區別,但也許你已經知道它了:?) – AgostinoX 2011-11-21 16:31:27