扩展一个JFrame与创建一个新的JFrame相比有什么优缺点?
例如:
public class Test extends JFrame {
setVisible(true);
}
或者public class Test {
JFrame test = new JFrame():
test.setVisible(true);
}
扩展一个JFrame与创建一个新的JFrame相比有什么优缺点?
例如:
public class Test extends JFrame {
setVisible(true);
}
或者public class Test {
JFrame test = new JFrame():
test.setVisible(true);
}
如果你不想扩展一个类的功能,那么就不应该去继承它。在你提供的例子中,应该使用选项2,因为选项1滥用了extend
特性。
换句话说,只要回答问题“Test是JFrame吗?”的答案是“不是”,就不应该继承JFrame
。
不扩展JFrame(或任何Swing组件)的优点:
int getX()
和int getY()
方法时。尝试一下,你会发现一些不太有趣的异常行为。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);
}
...
}