Good evening,
I'd like to know how to get the size of a JComponent after it's been laid out with a LayoutManager. I've read that this is possible, if you just call dolayout(), validate(), or setVisible() beforehand. However, I can't get it to work in my code.
The reason I'd like to know this is to only add as many components as will fit in the frame's set size, while not knowing the size of the components beforehand. Calling validate() doesn't set the size of the components in this code sample. Any ideas on how I can get the right size?
public class TestFrame extends JFrame {
public static void main(String args[]) {
TestFrame frame = new TestFrame();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public TestFrame() {
super("Test Frame");
super.setSize(300, 600);
this.addComponents();
}
private void addComponents() {
int heightLeft = this.getHeight();
JPanel panel = new JPanel();
panel.setSize(300, 600);
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
String text = "This is a long String that represents "
+ "the length of strings in my application. "
+ "This will vary in the real application."
+ "<ul><li>It uses html</li><li>not just</li>"
+ "<li>plain text</li></ul>"
+ "I'd like as many as will fit in the fame to be added.\n";
while (true) {
JTextPane textPane = createTextPane(text);
this.invalidate();
if (heightLeft > 0) {
panel.add(textPane);
} else {
break;
}
System.out.println("Before validation:" + textPane.getSize());
// returns width and height = 0
this.validate();
System.out.println("After validation:" + textPane.getSize());
// Still returns width and height = 0
heightLeft -= textPane.getPreferredSize().getHeight();
}
super.add(panel);
}
public JTextPane createTextPane(String text) {
JTextPane textPane = new JTextPane();
textPane = new JTextPane();
textPane.setEditorKit(new StyledEditorKit());
textPane.setEditable(false);
textPane.setOpaque(false);
textPane.setContentType("text/html");
textPane.setText(text);
return textPane;
}
}
Thanks for your time!