JFrame 关闭按钮的弹出窗口

2022-01-24 00:00:00 java swing jframe windowlistener jpopup

我正在做一些基本的 Java Swing 应用程序(初级).我要做的是当我按下 JFrame 上的 close 按钮​​ 来关闭我想要一个 JOptionPane 确认对话框 而不是直接关闭的窗口时

i am doing some basic Java Swing application (beginner level) . what i have to do is when i press close button on JFrame to colse the window i want a JOptionPane Confirm Dialog instead of straightforward close

这里是代码 JFrame

here is the code JFrame

   JFrame  frame= new JFrame("frame"); 
   frame.setSize(300,300);
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.setVisible(true);
   frame.pack();

JOptionPane 代码是这样的

and JOptionPane code goes like this

   final JOptionPane optionPane = new JOptionPane("Are You sure?",JOptionPane.QUESTION_MESSAGE,
JOptionPane.YES_NO_OPTION);

所以当按下 JFrame 上的关闭按钮时,这个弹出窗口应该出现而不是直接关闭
请指导我如何做到这一点..提前谢谢

so when Close button on JFrame pressed this popup should come up instead of Direct closing
Please guide me how i can do it .. Thanks in advance

推荐答案

您可以按照以下步骤进行:

You can do it by following steps:

  1. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 行替换为 frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

实现 WindowListener 并覆盖其所有抽象方法.您可以在这里找到它.

Implement WindowListener and override its all abstract methods. You can find it here.

以这种方式覆盖 public void windowClosing(WindowEvent e) 方法:

Override the public void windowClosing(WindowEvent e) method some this way:

 @Override
 public void windowClosing(WindowEvent e){
       int result = JOptionPane.showConfirmDialog(null, "Are you sure,"Confirm",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE);

       if(result == JOptionPane.YES_OPTION){
               System.exit(0);
       }else{
               //Do nothing
       }
 }

相关文章