Java jFrame关闭按钮

时间:2014-04-20 17:01:01

标签: java swing 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
    {
    }

    }
    }); 

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

2 个答案:

答案 0 :(得分:3)

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

myJFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

然后按关闭按钮不会关闭JFrame,您必须在代码中处理它。

答案 1 :(得分:1)

将默认关闭操作设置为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  
    }  
}