If you have direct access to the main frame, you can call JFrame#pack
which will validate the container hierarchy and layout all the child components, for example...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.LineBorder;
public class BeforeVisible {
public static void main(String[] args) {
new BeforeVisible();
}
public BeforeVisible() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TestPane center = new TestPane(100, 100);
frame.add(center);
frame.add(new TestPane(100, 50), BorderLayout.NORTH);
frame.add(new TestPane(100, 50), BorderLayout.SOUTH);
frame.add(new TestPane(50, 100), BorderLayout.EAST);
frame.add(new TestPane(50, 100), BorderLayout.WEST);
System.out.println("Size beofre pack = " + frame.getSize() + "; " + center.getSize());
frame.pack();
System.out.println("Size after pack = " + frame.getSize() + "; " + center.getSize());
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private int pWidth, pHeight;
public TestPane(int width, int height) {
pWidth = width;
pHeight = height;
setBorder(new LineBorder(Color.RED));
}
@Override
public Dimension getPreferredSize() {
return new Dimension(pWidth, pHeight);
}
}
}
Which outputs....
Size beofre pack = java.awt.Dimension[width=0,height=0]; java.awt.Dimension[width=0,height=0]
Size after pack = java.awt.Dimension[width=200,height=222]; java.awt.Dimension[width=100,height=100]
Now, if you don't have direct access to the main window, anything you do will be purely guess work.
You could also add a ComponentListener
to the component(s) you are interested and monitor their changes in size...but this then raises the question of "why?"