Swing:设置JFrame内容区域大小
我正在尝试制作一个可用内容区域正好为500×500的JFrame。 如果我这样做……
public MyFrame() { super("Hello, world!"); setSize(500,500); }
…我得到一个全尺寸为500×500的窗口,包括标题栏等,我真的需要一个窗口,其大小类似于504×520,以便考虑窗口边框和标题栏。 我怎样才能做到这一点?
你可以尝试几件事: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-更便携
只需使用:
public MyFrame() { this.getContentPane().setPreferredSize(new Dimension(500, 500)); this.pack(); }
如果您只想设置框架的大小,则不需要JPanel。
没关系,我想通了:
public MyFrame() { super("Hello, world!"); myJPanel.setPreferredSize(new Dimension(500,500)); add(myJPanel); pack(); }