按YES之前确认退出Java程序
private void windowClosing(java.awt.event.WindowEvent evt) { int confirmed = JOptionPane.showConfirmDialog(null, "Exit Program?","EXIT",JOptionPane.YES_NO_OPTION); if(confirmed == JOptionPane.YES_OPTION) { dispose(); } }
我想通过按确认关闭窗口按钮关闭程序…但是当我选择“否”返回我的Jframe时,它仍然可以帮助我退出程序???
从我的理解,你想要这样的东西
addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { int confirmed = JOptionPane.showConfirmDialog(null, "Are you sure you want to exit the program?", "Exit Program Message Box", JOptionPane.YES_NO_OPTION); if (confirmed == JOptionPane.YES_OPTION) { dispose(); } } });
如果你想在某个按钮上使用它,请按下类似的function。 把听众放在上面并做同样的事情。 但我不确定我的问题是否正确。 但是如果要使用按钮使用ActionListener和动作执行的方法。
check question – Java – 关闭JFrame窗口时的消息
addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent evt){ int x = JOptionPane.showConfirmDialog(null, "Are you sure you want to exit ?", "Comform !", JOptionPane.YES_NO_OPTION); if(x == JOptionPane.YES_OPTION) { setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); }else{ setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); } } });
谢谢这个。
试试这个,它对我有用。
private void windowClosing(java.awt.event.WindowEvent evt) { int confirmed = JOptionPane.showConfirmDialog(null, "Exit Program?","EXIT",JOptionPane.YES_NO_OPTION); if(confirmed == JOptionPane.YES_OPTION) { dispose(); } } else { setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);