0

So I have two classes, Main and MakeUserWindow, inside of my Main class I call MakeUserWindow several times with different parameters by using a loop. The only problem is, this creates several windows that overlap each-other (Which isn't that much of a deal, it's just that I can get 20 windows on top of each-other). What I thought of doing was simply using window.dispose(); right before recalling the instance, however, when I do that it closes all instances of the window. Not allowing me to recreate the instance using the same variable. Is there a way of closing only the single instance like window.close(); that I am unaware about, or am is there just a better way of doing this? I have searched for awhile before coming here, no results have helped.

For some reference, here is a simplified version of what I am doing

(MakeUserWindow is a class that extends JFrame)

MakeUserWindow newWindow;

for(stuff){

    newWindow.dispose();
    newWindow = new MakeUserWindow("parameters here");
}

EDIT--- The reason I initialize MakeUserWindow outside of the loop is because I need to use newWindow's properties.

Thanks for reading, -Zach.

Althonos
  • 131
  • 1
  • 9
  • Can you provide the code where you instantiate all the MakeUserWindows, or is this it? From the logic you've presented, "orphaned" windows shouldn't be getting closed. – Compass Sep 26 '14 at 19:40
  • 1
    [See here](http://stackoverflow.com/questions/1234912/how-to-programmatically-close-a-jframe) how to close a JFrame – Benvorth Sep 26 '14 at 20:13
  • I call MakeUserWindow in several different locations, each time I call it I pass a string to it that determines what window is created, such as "idWindow", "addWindow", etc. This make user window isn't actually called in a for loop, but in a method that is called several times throughout the program. – Althonos Sep 26 '14 at 20:27
  • 1
    See [The Use of Multiple JFrames, Good/Bad Practice?](http://stackoverflow.com/q/9554636/418556) – Andrew Thompson Sep 27 '14 at 01:08

1 Answers1

1

I had tested it and this is what i got:

    JFrame frame = new JFrame();
    for (int i = 0; i < 5 ; i++) {
        frame.dispose();
        frame = new JFrame();
    }

More or less like your code. Only the last frame survived cause you are closing the others when you do the ".dispose()". What you can do is a Map that keeps all the instances.

    Map<String, JFrame> frames = new HashMap<String, JFrame>();
    JFrame frame = new JFrame();
    for (int i = 0; i < 5 ; i++) {
        frame = new JFrame();
        frames.put("Window" + i,frame);
    }

And if you want to close a frame you do:

frames.get("WindowX").dispose();