简体   繁体   English

防止java从同一窗口的多个开口-JFrame

[英]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? 因此创建了名为Autor的对象,当我再次单击该按钮时,它会再次弹出相同的Autor对象..如果已打开一个窗口,如何阻止打开同一个窗口?

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: 经过大量的思考...我做了我的解决方案... autorOpen =“no”的默认值我在课程开始时声明,只是为了让你知道,因为它在下面的代码中不可见,解决方案本身:

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). 您还可以考虑将Autor实现为单例类(以确保只实例化一个)。

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. 如果弹出对话框,则将其设置为true,并在关闭该对话框时将其设置为false。

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. 一种解决方案是在发生任何点击之前创建autor,然后让事件将其从隐藏移动到可见。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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