防止java多次打开同一个窗口-JFrame
例如,我在单击时创建了此
//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");
}
});
对象,因此创建了名为 Autor 的对象,当我再次单击按钮时,它会再次弹出相同的 Autor 对象。如果已经打开了一个窗口,如何防止打开同一窗口?
编辑:终于有解决方案了! 经过很多思考......我做出了我的解决方案...... 我在课程开始时声明了 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);
}
});
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);
}
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
将变量存储在全局范围内,并在创建新变量之前检查它是否存在。
Store the variable a little bit more globally, and check whether it exists before creating a new one.
您还可以考虑将 Autor 实现为单例类(以确保只有一个被实例化)。
You could also consider implementing Autor as a singleton class (to ensure only one is ever instantiated).
使用布尔标志来指示对话框是否启动。如果弹出对话框,则将其设置为 true;如果关闭该对话框,则将其设置为 false。
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.
如果您每次点击时都创建“新”内容,则每次都会看到一个新窗口。一种解决方案是在发生任何点击之前创建 autor,然后让事件将其从隐藏移动到可见。
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.