0

I'm trying to keep this fairly clean and on a single reference to a JFrame, a cut and skinned version of the application is as follows:

public class Client extends SuperclassNotJFrame

     private JFrame frame;

     method a()
        frame = new Frame("first frame").setSize(400,400).setVisible(true)
     endmethod

     method b()
        frame = new Frame("second frame").setSize(800, 600).setVisible(true)
     endmethod

endclass

If I call method a() and then later call method b(), the frame created during method a() will stay, even though I've completely removed the reference the frame created there by over-writing it with the new frame.

I've even tried doing frame = null in b(), with the same result.

APerson
  • 8,140
  • 8
  • 35
  • 49
Hobbyist
  • 15,888
  • 9
  • 46
  • 98
  • 3
    Take a look at [The Use of Multiple JFrames, Good/Bad Practice?](http://stackoverflow.com/q/9554636/418556) and [How to Use CardLayout](http://docs.oracle.com/javase/tutorial/uiswing/layout/card.html) or [How to Make Dialogs](http://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html) depending on your needs – MadProgrammer Dec 01 '14 at 00:40

1 Answers1

1

To make frame invisible, you can use frame.setVisible(false);.

The object you created by calling the Frame constructor in method a() is not deleted immediately when the reference stops pointing to it. When you called setVisible(true) on the frame from a(), you created a window that will persist even after a() terminates.

APerson
  • 8,140
  • 8
  • 35
  • 49
  • But if the `frame` is overwritten, how is the reference to the old frame not destroyed? – Hobbyist Dec 01 '14 at 00:40
  • Considering the edit to your question, how would i go about "deleting" the old frame properly. Shouldn't just removing the reference "delete" it and make it eligible for `gc()` – Hobbyist Dec 01 '14 at 00:43
  • Thanks, the setVisible edit helps, so as-long as `a()->visible` the garbage collector will ignore it, even if `frame != a` right? – Hobbyist Dec 01 '14 at 00:44
  • 1
    The *object* that `frame` points to in `a()` is garbage-collected eventually. You can't really delete a `JFrame`; if you want it to disappear on the screen (which I believe is your goal), simply call `setVisible(false);` on it. – APerson Dec 01 '14 at 00:48
  • 1
    I'm not 100% certain on whether or not references to the frame object persist; the Swing framework may be keeping it alive in some way, but the garbage collector only considers references to an object when deciding whether to delete it. – APerson Dec 01 '14 at 00:50