我想知道是否有任何以编程方式创建JFrame的方法,这是正确的

JFrame frame = new JFrame("title");
            frame.pack();
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            frame.setVisible(true);
            frame.setSize(250,200);
      or

JFrame frame = new JFrame("title");
            frame.setSize(250,200);
            frame.pack();
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            frame.setVisible(true);

      or
JFrame frame = new JFrame("title");
            frame.setSize(250,200);
            frame.pack();
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            frame.setVisible(true);

现在,此代码可以通过简单的程序正常运行,但是如果我在更大的程序中使用线程呢?

最佳答案

如果使用正确的布局管理器并调用setSize(),则无需调用pack()方法。如果您确实需要绝对大小,请覆盖JPanelJComponent#getPreferredSize()方法。

阅读更多Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?
添加所有组件后,最后调用setVisible()方法。不要在顶层容器中直接添加组件。使用其他容器,例如JPanel,最后将其添加到JFrame中。
调用setDefaultCloseOperation()方法的顺序无关紧要。

10-07 16:51
查看更多