简体   繁体   中英

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);  
            }
        });

全局存储变量,并在创建新变量之前检查它是否存在。

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;
}
}

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM