I have JEditorPaneone that appears inside a popup that starts with a button. The panel contains long text, so it is nested inside JScrollPane, and the popup is limited to a maximum size of 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);
}
});
}
When an instance is JEditorPanedisplayed for the first time (i.e., when the button is pressed once), it somehow seems to indicate a preferred height that is too low (1) :

After subsequent mouse clicks, the layout is how you would expect it (2) :

How can I ensure / overlay the correct preferred size so that it always initializes as (2)?