1

I have a problem with understanding the following code:

import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.*;

public class A
{
      public A(){
        JFrame myframe = new JFrame ("hz window");
        myframe.setLayout(new GridLayout ());
        myframe.setSize(new Dimension (500, 200));
        myframe.setVisible(true);
    }

    public static void main (String arg[]){
        new A();
        //  System.gc();                          //1
          //Runtime.getRuntime().gc();            //2
    }
}

The scope of myframe object is the constructor of class A,right?

Then, why is the window not dissapeared (i.e.,removed by garbage collector in lines 1 and 2)

What is the scope of all gui elements we create in java program?

Where does JVM keep all the links to the application's gui objects?

I'm sorry for newbie questions.

Evgenii.Balai
  • 889
  • 11
  • 27

4 Answers4

7

Swing keeps a reference to every window object until they are closed by user or disposed forcefully using dispose() function. Otherwise, you would see mysteriously dissapearing GUI elements.

Eser Aygün
  • 6,566
  • 1
  • 17
  • 26
2

The EventDispatchThread where the Swing code executes.

Bogdan T.
  • 658
  • 5
  • 12
2

Top-Level Containers never gone from JVM Memory, nor could be disposed or GC'ed, because:

  • missing method finalize in the API,

  • Top-Level Containers came from Native OS,

  • can garbage only its Graphics(2D) (after removing its contents), then there is/are only empty container(s),

  • untill current JVM instance exist then you can re_use this/these container(s), more here

Community
  • 1
  • 1
mKorbel
  • 108,320
  • 17
  • 126
  • 296
1

A Jframe is closed using the method dispose so if you want to close you're jframe juste do that

public static void main (String arg[]){
    Jframe a = new A();
    //do what ever you want and when it's done

    a.dispose();
}

the garbage collector is not here in java to close everything, and a jframe is in it's own thread, so it's complicated to determined if it needs to be erase or not.

Moreover, JFrame is a independant thread, and it's usually close by clicking the X in the top right corner of the frame, so a better solution might be to set the default behaviour of this action to dispose

public A(){
    JFrame myframe = new JFrame ("hz window");
    myframe.setLayout(new GridLayout ());
    myframe.setSize(new Dimension (500, 200));
    myframe.setVisible(true);
    myframe.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
}

but it depend of what you want to do with your frame after.

Kiwy
  • 187
  • 2
  • 7
  • 38