摆动:设置 JFrame 内容区域大小

2022-09-01 16:41:22

我正在尝试制作一个可用内容区域正好为500x500的JFrame。如果我这样做...

public MyFrame() {
    super("Hello, world!");
    setSize(500,500);
}

...我得到一个全尺寸为500x500的窗口,包括标题栏等,我真的需要一个大小为504x520的窗口来考虑窗口边框和标题栏。我怎样才能做到这一点?


答案 1

你可以尝试以下几件事:1 - 一个黑客:

public MyFrame(){
 JFrame temp = new JFrame;
 temp.pack();
 Insets insets = temp.getInsets();
 temp = null;
 this.setSize(new Dimension(insets.left + insets.right + 500,
             insets.top + insets.bottom + 500));
 this.setVisible(true);
 this.setResizable(false);
}

2- 或将 JPanel 添加到框架的内容窗格,只需将 JPanel 的首选/最小大小设置为 500X500,调用 pack()

  • 2-更便携

答案 2

只需使用:

public MyFrame() {
    this.getContentPane().setPreferredSize(new Dimension(500, 500));
    this.pack();
}

没有必要在那里放置JPanel,如果你只是想设置框架的大小。


推荐