Tom Sprud
Tom Sprud

Reputation: 57

Java : Instantiating method variables

I'm relatively new to Java programming and might have missed something obvious so bear with me.

I'm creating a program that uses the Swing API with JDesktopPane to create a GUI. On the main screen is a button that says 'New Window'. The user clicks it and a new JInternalFrame is instantiated and added to the JDesktopPane. As in the following, simplified, method:

protected void createNewWindow(JPanel panel) {

    JInternalFrame fooFrame = new JInternalFrame();
    fooFrame.setContentPane(panel);
    desktop.add(fooFrame);
}

My question is this. Say the user clicks the button ten times. Ten JInternalFrames are created. All of them are method variables so they have the same name.

What happens to these old fooFrame variables? Does the garbage collector come and destroy them at any stage? I wouldn't have thought anything is still holding a reference to them. Is there any way to access any of these old fooFrames? Say I wanted to change the text colour on a JPanel on the fourth out of ten fooFrames. Any way to do this?

I know this is a very stupid way to do things, and it's simple to just create a JInternalFrame instance variable, possibly an array, to instantiate in the method and add to the JDesktopPane. My question was more out of curiosity than anything.

Upvotes: 0

Views: 606

Answers (1)

Habib
Habib

Reputation: 223247

What happens to these old fooFrame variables? Does the garbage collector come and destroy them at any stage?

Your object desktop is holding reference to the fooFrame created in the method, each of them will have a differnet reference and will be maintained by desktop. Once the desktop goes out of scope they will be eligible for garbage collection. Usually method variables are eligible for garbage collection after the control comes out of the method, since they are maintainied inside the method scope, but in your case, you have desktop which is maintained at class level.

Upvotes: 2

Related Questions