Hi,
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.
-
Is this happening because the subclass is inheriting the superclass constructor and therefore creating another window?
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:public class Deck extends JFrame { public Deck(boolean createContent) { if( createContent ) { getContentPane().add(...); // ... } } public Deck() { this(true); } } public class Pile extends Deck { public Deck() { super(false); // ... } }
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.
Kari : Thanks I will try that. Basically I want to make use of the GUI components that are created in Deck, from other classes. At the moment I am working around it by making these component variables static and accessing them from the other classes by using Deck.JPanel1, for example. But I think there are better ways of doing it...From Peter Lang -
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 usingsetVisible(false)
inPile
's constructor, but that would be strange.You should redefine your inheritance hierarchy.
Kari : is it possible to override the superclass's constructor?Peter Lang : @Kari: No. The super-constructor will be called implicitely before your constructor is called. Please provide more information about why you want to extend a class but not use its behavior.From Bozho -
Ya its happening because the subclass is inheriting the super class constructor.In any subclass always first super class constructor is called.
From giri
0 comments:
Post a Comment