-4

I have a quick question regarding JFrames and disposing them properly. I have a game that has multiple levels, I wish to dispose of the frame in use when another is created with a new level.

The program I am currently working on extends a JFrame which has always confused me as I don't know what that JFrame is called.

Anyway, I have another class that extends a JPanel. In this class I have a method that, when the game state is completed, removes all instances and closes the JFrame. Yet this does not work because I cannot get the frame of the frame, instead I get multiple instances of the same JFrame.

So my set up looks like this:

Class 1 extends JFrame .... .... ....

Class 2 extends JPanel ... ... method(clears everything + gets new JFrame for new level) ...

Sorry if that is vague, I don't want to post hundreds of lines of code for a short question. I know others have asked this question but I can never seem to get it to work for me.

So once again, my question is simply how do you close a JFrame in another class method.

(Please note everything works perfectly, I just can't close the frame without it breaking completely on me)

  • 3
    You're right, that is vague. Try to build an http://stackoverflow.com/help/mcve – pvg Dec 21 '15 at 17:41
  • 4
    You should avoid the use of multiple JFrames, see [The use of multiple JFrames, Good/Bad Practice](http://stackoverflow.com/questions/9554636/the-use-of-multiple-jframes-good-bad-practice) instead use a [CardLayout](https://docs.oracle.com/javase/tutorial/uiswing/layout/card.html) – Frakcool Dec 21 '15 at 17:44
  • 1
    A better solution might to use a [CardLayout](http://docs.oracle.com/javase/tutorial/uiswing/layout/card.html) or more use of a [dialog](http://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html) – MadProgrammer Dec 21 '15 at 20:36

1 Answers1

3

dispose() is an insance-level method. If you have object o, which is of JFrame or an inherited class, then o.dispose() should dispose it. If you are not sure that o is initialized when you want to dispose it, then

if (o != null) {
    o.dispose();
}

If you simply call dispose() from somewhere, you will get an exception if that object/class does not have a dispose object. So, if you want to dispose o from class A, then you should call o.dispose() in one of the methods, but make sure that you initialize o correctly before that.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175