gpt4 book ai didi

java - 使 JOptionPane 消失

转载 作者:行者123 更新时间:2023-12-01 18:36:36 26 4
gpt4 key购买 nike

public void windowClosing (WindowEvent e)
{
JFrame frame = new JFrame();

int confirm = JOptionPane.showConfirmDialog (frame, "Exit game?", "Are you sure?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (confirm == JOptionPane.YES_OPTION)
{
dispose ();
}
else
{
frame.setVisible(false);
}
}

因此,当用户单击关闭按钮时,会弹出一个 JOptionPane。当用户单击“否”时,JOptionpane 应该消失,然后返回到它最初显示的框架,但使用我的代码,即使我单击“否”,两个框架(JOptionPane 的框架和它所在的框架)开启,消失。

有一件事:

  • 我知道我不应该为 JOptionPane 创建新的 JFrame,但我尝试使用 this 作为组件,例如: JOptionPane.showConfirmDialog (this, "...",. ..) 当用户单击“否”时,JOptionPane 是唯一应该消失的东西(所以我将其设置为:this.setVisible(false);)但是当我使用 this 即使主框架消失,所以我只想创建一个新框架来满足我的需求。我也无法将其设置为 null,因为我需要它出现在屏幕中央。如果有人可以建议我如何处理这个问题,请告诉我。

最佳答案

这真的很简单,你的框架消失了,因为你说它不应该是可见的,只需删除其他的:

public void windowClosing (WindowEvent e) {         
int confirm = JOptionPane.showConfirmDialog (this, "Exit game?", "Are you sure?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);

if (confirm == JOptionPane.YES_OPTION) {
dispose();
}
}

编辑:

同时将 setDefaultCloseOperation (EXIT_ON_CLOSE); 替换为 setDefaultCloseOperation (DO_NOTHING_ON_CLOSE);,否则无论 windowClosing 方法中发生什么情况,主框架都会关闭。

关于java - 使 JOptionPane 消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21729529/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com