[英]Extending a JFrame
What are the pros and cons of extending a JFrame rather than create a new JFrame ? 扩展JFrame而不是创建新的JFrame有什么优缺点?
For example: 例如:
public class Test extends JFrame {
setVisible(true);
}
or 要么
public class Test {
JFrame test = new JFrame():
test.setVisible(true);
}
You should not extend a class, unless you want to actually extend its functionality, in the example you've shown, you should use option 2, as option 1 is an abuse of the extend
ing feature. 您不应该扩展类,除非您想要实际扩展其功能,在您显示的示例中,您应该使用选项2,因为选项1是滥用
extend
功能。
In other words - as long as the answer to the question is Test a JFrame
? 换句话说 - 只要问题的答案是Test a
JFrame
? is NO , it should not extend JFrame
. 是NO ,它不应该扩展
JFrame
。
pros of not extending JFrame (or any Swing component for that matter): 没有扩展JFrame(或任何Swing组件)的优点:
int getX()
and int getY()
methods. int getX()
和int getY()
方法。 Try it and you'll see some not so funny abnormal behaviors. If extending JFrame, I would want to modify/customize my current Jframe class and so subclass can use this customized implementation. 如果扩展JFrame,我想修改/自定义我当前的Jframe类,因此子类可以使用这个自定义的实现。
If there nothing that I want to do change in the JFrame class, just use the existing like in second snippet that you've given in your code. 如果在JFrame类中没有任何我想要做的更改,只需使用您在代码中给出的第二个片段中的现有内容。 By use, I mean by creating other JComponent (button/label for examples), etc, in a JPanel and create an object Test and set the JFrame contentPane to this object.
通过使用,我的意思是在JPanel中创建其他JComponent(示例的按钮/标签)等,并创建一个对象Test并将JFrame contentPane设置为此对象。 Something like
就像是
public class Test extends JPanel {
public class() {
// add buttons/label here
}
...
private static void createAndShowGUI() {
JFrame frame = new JFrame();
Test object = new Test();
frame.setContentPane(object.setOpaque(true));
frame.setVisible(true);
}
...
}
One of the rules of OOD: If you can not inherit (extend) the classes you do not inherit their. OOD的一个规则:如果你不能继承(扩展)你不继承它们的类。
Inheritance increases the complexity and connectedness of the program and potentially lead to new errors. 继承增加了程序的复杂性和连通性,并可能导致新的错误。 In your case there are not any reasons to extend class.
在您的情况下,没有任何理由扩展课程。
You should extends classes only when you need to get access to protected members and/or or get polymorphic behavior (override virtual methods). 只有在需要访问受保护成员和/或获取多态行为(覆盖虚方法)时,才应扩展类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.