【发布时间】:2012-01-08 02:32:42
【问题描述】:
当我在第一门 Java 课程中学习创建 Java GUI:s 时,我被教导将我的窗口创建为 JFrame 实例,然后为每个 JFrame 添加一个 JPanel,最后将所有 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 来包装其他组件。但是除了这些之外,这些方法之间的真正区别是什么?他们中的任何一个都比另一个有什么好处吗?
【问题讨论】:
-
很棒的教程!我建议任何发现此问题的人阅读它。
-
没关系(两者都不好,也不需要做,只需添加到框架中) - 真正的气味是 extends JFrame :good ol' OO 规则是仅当存在合理的 is-a 关系时才进行扩展(与仅使用情况相比,所有 gui 应用程序中 99.99% 的情况都是如此)