3

I am in the Beginner phase of learning Java. In all docs I have read till now, its mentioned that Java uses secure references to access objects instead of memory pointers. And also that when a method returns, its locally scoped variables become eligible for Garbage Collection.

So why in this below code, the JFrame object isn't destroyed along with the window after the createFrame method returns?

import javax.swing.*;

public class HelloJava {
    public static void main( String[] args ) {
        createFrame();
    }

    private static void createFrame() {
        JFrame frame = new JFrame( "Hello, Java!" );
        JLabel label = new JLabel( "Hello, Java!", JLabel.CENTER );
        frame.getContentPane().add( label );
        frame.setSize( 300, 300 );
        frame.setVisible( true );
    }
}

Not only the window is visible, I can do all the actions on that window like drag, maximize, minimize etc.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
anilmwr
  • 477
  • 9
  • 16

2 Answers2

6

Because the EDT is now running.

For more details, see Concurrency in Swing & particularly:

  • Initial Threads.

    In standard programs, there's only one such thread: the thread that invokes the main method of the program class.

  • The Event Dispatch Thread.

    Swing event handling code runs on a special thread known as the event dispatch thread. Most code that invokes Swing methods also runs on this thread.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
6

The JFrame object isn't destroyed because the UI Thread or so called Event Dispatch Thread has a reference to it and is actively using it.

Reimeus
  • 158,255
  • 15
  • 216
  • 276