如果您可以直接访问主框架,则可以调用JFrame#pack
which 将验证容器层次结构并布局所有子组件,例如...
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);
}
}
}
哪个输出......
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]
现在,如果您无法直接访问主窗口,那么您所做的任何事情都只是猜测。
您还可以将 a 添加ComponentListener
到您感兴趣的组件中并监视它们的大小变化......但这会引发“为什么?”的问题。