Java jFrame关闭按钮



嗨,我有一个jFrame,我想问用户,当点击关闭按钮时,他是否确定要关闭jFrame:

    this.addWindowListener(new java.awt.event.WindowAdapter() {
    @Override
    public void windowClosing(java.awt.event.WindowEvent windowEvent) {
    Main ma = new Main();
    Object[] options = {"Yes", "NO"};
    int selectedOption = JOptionPane.showOptionDialog(ma, "Are you sure you want to close the system?", "Warning",
    JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
    null, options, options[0]);
           if (selectedOption == JOptionPane.YES_OPTION) {
               System.exit(0);
           }
    else
    {
    }
    }
    }); 

当他从弹出窗口中选择"否"按钮时,我该如何撤消关闭操作?

首先,您需要将JFrame的默认关闭操作设置为在关闭时不执行任何操作:

myJFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

然后按下关闭按钮将不会关闭JFrame,您将不得不在代码中处理它。

将默认关闭操作设置为JFrame.DO_NOTHING,然后使用WindowListener并侦听windowClosing事件。现在要关闭帧,只需在帧上调用dispose()即可。因此:

public void windowClosing(WindowEvent e)  
{  
    JFrame frame = (JFrame)e.getWindow();  
    if (canClose(frame)) // you define canClose  
    {  
        frame.dispose();  
    }  
    else  
    {  
        // other stuff  
    }  
} 

最新更新