我刚刚读了这个答案https://stackoverflow.com/a/15560624/3211987,但是如果我为循环添加,第一个JFrame的大小是可以的,但是其他JFrame的大小要大10像素。这是功能吗?还是为什么会这样?
仅当两次调用frame.pack()时,最终大小才正确。
public class TestResizableFrame {
public static void main(String[] args) {
for (int i = 0; i < 25; ++i)
new TestResizableFrame();
}
public TestResizableFrame() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new FixedPane());
frame.setResizable(false);
frame.pack(); // if called twice, the size is correct
// frame.pack(); // uncomment to get correct size
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class FixedPane extends JPanel {
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Dimension size = getSize();
String text = size.width + "x" + size.height;
FontMetrics fm = g.getFontMetrics();
int x = (getWidth()- fm.stringWidth(text)) / 2;
int y = ((getHeight() - fm.getHeight()) / 2) + fm.getAscent();
g.drawString(text, x, y);
g.setColor(Color.RED);
g.drawRect(0, 0, 199, 199);
}
}
}
最佳答案
这是一个非常有趣的问题,困扰了我很多。通过反复尝试,我找到了对我来说似乎可靠的解决方案。
您必须在setVisible
之后和setResizable
之前致电pack
frame.add(new FixedPane());
frame.setResizable(false);
frame.setVisible(true);
frame.pack();
问题仍然存在,为什么必须这样。没有记录这些调用的顺序。