开发者

When a superclass extends JFrame

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 a JFrame.

super() is always called implicitely before your own constructor, unless you call super(...) or this(...) 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 your Deck-class are not created.

I'm not sure why you want to do this, so maybe you can add more information to clearify.


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) in Pile'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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜