我应该继承 JFrame/JPanel 吗? [英] Should I subclass JFrame/JPanel or not?

查看:37
本文介绍了我应该继承 JFrame/JPanel 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我习惯于在其他编程环境中对窗口类进行子类化,但在 java 教程中我通常会看到类似

I was used to subclassing the window-classes in other programming environment, but in the java tutorials I usually see something like

JPanel p = new JPanel();
p.setLayout(new BoxLayout(p, BoxLayout.PAGE_AXIS));

p.add(aComponent);
p.add(anotherComponent);

Java 中关于子类化顶级容器类的约定是什么?

So what are the conventions in Java regarding subclassing top-container classes?

推荐答案

使用与所有 Java 类相同的原则.如果您正在修改或扩展行为或功能,那么一定要扩展 JPanelJFrame.诀窍是仔细考虑并决定是否真的要添加任何东西.在大多数情况下,当我看到人们扩展 JFrame 时,这是不必要且错误的;

Use the same principle as you would for all java classes. If you are modifying or extending the behaviour or functionality, then by all means, extend JPanel or JFrame. The trick is to think carefully and decide if you really are adding anything. In most cases when I see people extending JFrame it is unnecessary and wrong;

public class MyFrame extends JFrame {
  public static void main(String[] args) {
    new MyFrame().setVisible(true);
  }
}

为什么要扩展JFrame?你还没有添加任何东西!组合是一个更好的选择.

Why bother extending JFrame? You haven't added anything! Composition is a much better option.

扩展 JPanel 有点不同.JPanel 是一个相当抽象的概念,它只是其他组件的通用容器.恕我直言,将 JPanel 子类化以创建更具体的面板是有效的,然后在您的应用程序中使用它.它促进了 OOP 和封装.

Extending JPanel is a little different. JPanel is a fairly abstract idea, its just a generic container for other components. IMHO it is valid to subclass JPanel to create a more concrete panel, and then use that in your application. It promotes OOP and encapsulation.

例如,假设您的 GUI 有 2 个主要显示区域;一个带有一些按钮/控件/输入,另一个显示输出(例如在文本区域中).将 JPanel 子类化以创建包含按钮/控件/输入的 ControlPanel 是完全可以接受的.这将所有代码移动到一个漂亮整洁的模块中,清理包含和处理主 JFrame 的类.

For example, say your GUI had 2 main display areas; one with some buttons/controls/inputs and another which displayed output (eg in a text area). It is perfectly acceptable to subclass JPanel to create a ControlPanel that contains the buttons/controls/inputs. This moves all the code into a nice neat module, cleaning up your class that contains and handles the main JFrame.

这篇关于我应该继承 JFrame/JPanel 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆