【问题标题】:confirmation before press YES to exit program in Java在按 YES 退出 Java 程序之前确认
【发布时间】:2014-02-15 07:54:46
【问题描述】:
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 时,它​​仍然可以帮助我退出程序???

【问题讨论】:

标签: java swing window jframe joptionpane


【解决方案1】:

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

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();
    }
  }
});

如果您想在某个按钮上使用它,请执行与按钮类似的功能。将听众放在上面并做同样的事情。但我不确定你的问题是否正确。但是如果你想使用按钮使用 ActionListeneraction executed 方法。

检查问题 - Java - Message when closing JFrame Window

【讨论】:

  • 但我不能为自己添加“addWindowsListener”..因为代码是用我的程序自动生成的
  • 你这是什么意思?您使用窗口生成器?如果是,那么您仍然可以修改任何您喜欢的内容并将其添加到您的任何 gui 部分
  • 应该在if条件下添加else if(confirmed == JOptionPane.YES_OPTION) { this.dispose(); } else { setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); } 现在运行良好
【解决方案2】:
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);
        }
    }
});

【讨论】:

    【解决方案3】:

    试试这个,它对我有用。

    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);
    

    【讨论】:

      猜你喜欢
      • 2014-09-09
      • 1970-01-01
      • 2021-03-15
      • 2019-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-20
      • 1970-01-01
      相关资源
      最近更新 更多