我有一个JEditorPane
显示在弹出窗口中,通过按钮触发。窗格包含长文本,因此它嵌套在 aJScrollPane
中,并且弹出窗口的最大尺寸为 300 x 100:
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) 一样初始化?