我应该将组件添加到JFrame还是其contentPane?

Tom*_*han 6 java swing jframe

当我在我的第一个Java课程中学习创建Java GUI时,我被教会创建我的窗口作为JFrame实例,然后添加JPanel到每个窗口JFrame,最后将所有GUI组件添加到JPanel:

class Example extends JFrame {
    Example() {
        JPanel panel = new JPanel();
        this.add(panel);

        // Create components here and add them to panel
        // Perhaps also change the layoutmanager of panel

        this.pack();
        this.setVisibility(true);
    }

    public static void main(String[] args) {
        new Example();
    }
}
Run Code Online (Sandbox Code Playgroud)

我总是"好吧,这闻起来有点气味;我不喜欢创造一个额外的对象只是为了一个容器",但我不知道有任何其他方法去做,所以我继续使用它.直到最近,当我偶然发现这个"模式"时:

class AnotherExample extends JFrame {
    AnotherExample() {
        Container pane = this.getContentPane();

        // Add components to and change layout of pane instead

        this.pack();
        this.setVisibility(true);
    }

    public static void main(String[] args) {
        new AnotherExample();
    }
}
Run Code Online (Sandbox Code Playgroud)

对Java来说仍然是一个新手,我觉得第二种方法更好,因为它不涉及创建一个JPaneljust来包装其他组件.但是这些方法之间的真正区别是什么呢?他们中的任何一方是否有其他任何好处?

And*_*son 4

我更喜欢创建一个JPanel(作为 Swing 容器,可以有边框)并将其设置为内容窗格。

JComponent离开内容窗格需要进行强制转换,这比创建额外的组件更难闻。