当我在第一门Java课程中学习创建Java GUI:s时,就被教导要创建我的窗口作为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();
}
}
我总是尽管“嗯,这闻起来有点;我不喜欢创建一个额外的对象只是作为一个容器,”但是我不知道有其他方法可以做到,所以我继续进行下去。直到最近,当我偶然发现这个“模式”时:
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();
}
}
对于Java来说,它仍然是一个相当新的事物,我对第二种方法感觉更好,因为它不涉及创建JPanel
用于包装其他组件的正义。但是,除此以外,这两种方法之间的真正区别是什么?他们中的任何一个相对于另一个有什么好处吗?
我更喜欢创建一个JPanel
(作为Swing容器,可以有一个边框)并将其设置为内容窗格。
要JComponent
离开内容窗格,需要铸造,它的气味比创建额外的组件还要糟糕。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句