0

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Habib. Cleared it up for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.