当超类扩展 JFrame 时
我正在尝试使用扩展 JFrame 的类来构建 GUI。
ex : class Deck extends JFrame
GUI 是在其构造函数中构建的。
现在,当我从另一个类扩展 Deck 时,
例如: class Pile extends Deck
每当子类(Pile)的实例启动时,就会创建新窗口。
发生这种情况是因为子类继承了超类构造函数并因此创建了另一个窗口吗?
可以在不修改 Deck 超类的情况下避免这种情况吗?
谢谢。
I am trying to use a class which extends JFrame to build a GUI.
ex : class Deck extends JFrame
The GUI is built in its constructor.
Now when I extend Deck from another class,
ex : class Pile extends Deck
New windows are being created whenever an instance of the subclass (Pile) is started.
Is this happening because the subclass is inheriting the superclass constructor and therefore creating another window?
Can this be avoided without modifying the Deck superclass?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的。您扩展了一个
JFrame
,因此您得到了一个JFrame
。super()
始终在您自己的构造函数之前隐式调用,除非您自己调用super(...)
或this(...)
。这需要是您自己的构造函数中的第一次调用。如果您确实想要这种行为,您可以在基类 (
Deck
) 中编写另一个构造函数,如下所示:由于扩展了它,您仍然会得到一个
JFrame
,但是不会创建Deck
类的子组件。我不确定你为什么要这样做,所以也许你可以添加更多信息来澄清。
Yes. You extend a
JFrame
, so you get aJFrame
.super()
is always called implicitely before your own constructor, unless you callsuper(...)
orthis(...)
yourself. This needs to be the first call in your own constructor.If you really want that behavior, you could write another constructor in your base class (
Deck
) like that:You will still end up with a
JFrame
since you extend it, but the child components of yourDeck
-class are not created.I'm not sure why you want to do this, so maybe you can add more information to clearify.
不会。超级构造函数总是被调用。
但是既然你扩展了
JFrame
,那么不创建窗口有什么意义呢?您可以在 Pile 的构造函数中使用 setVisible(false) 来隐藏它,但这会很奇怪。
您应该重新定义您的继承层次结构。
No. The super constructor is always called.
But since you extend
JFrame
, what's the point of not creating a window?You can hide it using
setVisible(false)
inPile
's constructor, but that would be strange.You should redefine your inheritance hierarchy.
是的,它的发生是因为子类继承了超类构造函数。在任何子类中,总是调用第一个超类构造函数。
Ya its happening because the subclass is inheriting the super class constructor.In any subclass always first super class constructor is called.
做你想做的事情的唯一方法是编辑 Deck 类。
一个简单的方法就是在你的超类( init() )或其他东西中创建一个新方法,然后将所有代码放在其中而不是构造函数中。然后用空方法(或您自己的方法)覆盖子类中的 init() 方法。
或者,您可以在超类中使用参数创建一个新的构造函数,例如 yourConstructor(boolean doNothing)。然后,您在子类中调用此构造函数,以便它只执行该构造函数,而不执行您的默认构造函数。
The only way to do what you want is to edit the Deck class.
An easy way to do it is just to make a new method in your superclass (init() ) or something, and put all your code in there instead of your constructor. Then overwrite the init() method in your subclass with an empty method (or your own).
Or you could make a new constructor in your superclass with a parameter, like yourConstructor(boolean doNothing). Then you call this constructor in your subclass so it only executes that one and not your default constructor.