按YES之前确认退出Java程序

jef*_*leo 2 java swing window jframe joptionpane

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();
        }
    }
Run Code Online (Sandbox Code Playgroud)

我想通过按确认关闭窗口按钮来关闭程序......但是当我选择"否"返回我的Jframe时,它仍然可以帮助我退出程序???

Tom*_*iak 5

据我了解,你想要这样的东西

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();
    }
  }
});
Run Code Online (Sandbox Code Playgroud)

如果要在某些按钮上使用它,请对按钮执行类似的功能。将侦听器放在其上并执行相同操作。但是我不确定我是否能正确回答您的问题。但是,如果要使用按钮,请使用ActionListeneraction执行方法。

检查问题-Java-关闭JFrame窗口时的消息


Ude*_*ara 5

JFrame frame = new JFrame();

// ...

frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent evt) {
        int resp = JOptionPane.showConfirmDialog(frame, "Are you sure you want to exit?",
            "Exit?", JOptionPane.YES_NO_OPTION);

        if (resp == JOptionPane.YES_OPTION) {
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        } else {
            frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

谢谢这个.