[英]Should I add components to a JFrame or to its contentPane?
When I learned creating Java GUI:s in my first Java course, I was taught to create my windows as JFrame
instances, and then add a JPanel
to each JFrame
and finally add all the GUI components to the JPanel
: 当我在第一个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();
}
}
I always though "well, this smells a little; I don't like creating an extra object just to be a container," but I didn't know any other way to do it so I just went on with it. 我总是“好吧,这闻起来有点气味;我不喜欢创造一个额外的对象只是为了一个容器”,但我不知道有任何其他方法去做,所以我继续使用它。 Until recently, when I stumbled over this "pattern":
直到最近,当我偶然发现这个“模式”时:
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();
}
}
Still being quite new to Java, I feel better about the second approach just because it doesn't involve creating a JPanel
just to wrap the other components. 对于Java来说仍然是一个新手,我对第二种方法感觉更好,因为它不涉及创建
JPanel
只是为了包装其他组件。 But what are the real differences between the approaches, except from that? 但是这些方法之间的真正区别是什么呢? Does any one of them have any great benefits over the other?
他们中的任何一方是否比另一方有什么好处?
I prefer to create a JPanel
(which, being a Swing container, can have a border) and set it as the content pane. 我更喜欢创建一个
JPanel
(它是一个Swing容器,可以有一个边框)并将其设置为内容窗格。
To get a JComponent
out of the content pane requires casting, which has an even worse smell than creating an extra component. 要从内容窗格中获取
JComponent
,需要进行转换,这比创建额外组件的气味更差。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.