Игор
Игор

Reputation: 365

prevent java from multiple openings of the same window-JFrame

for example i create this on click

//this creates autor object with default constructor properties defined in autor class
menuAutor.addMouseListener(new MouseAdapter(){
            public void mouseClicked(MouseEvent e)
            {
                autor Autor = new autor("Autor");
            }
        });

so object named Autor is created, and when i click again on the button, it pops up again the same Autor object.. how can prevent opening the same window if one is already opened?

EDIT: FINALY A SOLUTION! After lots of thinking about this.. i made my solution... default value for autorOpen="no" i declaired at the beginning of my class, just to let you know because its not visible in code below, the solution itself:

public void mouseClicked(MouseEvent e)
            {
                if(autorOpen=="no") {
                autor Autor = new autor("Autor");
                autorOpen = "yes";
                Autor.addWindowListener(new WindowAdapter(){
                    public void windowClosing(WindowEvent e) 
                    {
                        autorOpen = "no";
                    }
                });
                }
                else 
                    JOptionPane.showMessageDialog(null, "Demo notice... you can't open that window again.. its opened already!","Error",JOptionPane.ERROR_MESSAGE);  
            }
        });

Upvotes: 1

Views: 4387

Answers (4)

John
John

Reputation: 196

You could also consider implementing Autor as a singleton class (to ensure only one is ever instantiated).

public class Autor {

private static Autor instance = null;

//Must be protected or private, get a reference to this class with getInstance().
protected Autor() {
}


/**
* Returns reference to this class - use in place of constructor
*/
public static Autor getInstance() {
if(instance == null) {
instance = new Autor();
}
return instance;
}
}

Upvotes: 1

Thomas
Thomas

Reputation: 5094

If you're creating something with 'new' on each click, you'll get a new window each time. One solution is to create autor before any clicks happen, then have the event move it from hidden to visible.

Upvotes: 0

Eng.Fouad
Eng.Fouad

Reputation: 117589

Use a boolean flag to indicate if the dialog is up or not. Set it to true if the dialog is popped up, and set it to false when you close that dialog.

Upvotes: 0

Tom van der Woerdt
Tom van der Woerdt

Reputation: 29975

Store the variable a little bit more globally, and check whether it exists before creating a new one.

Upvotes: 3

Related Questions