简体   繁体   English

JFrame默认关闭操作中可能有故障

[英]A probable malfunction in JFrame default close operation

I'm experiencing a few issues with the JFrame's DefaultCloseOperation. 我遇到了JFrame的DefaultCloseOperation的一些问题。 I'm using Netbeans. 我正在使用Netbeans。 I have set the close operation to custom code in the properties window of JFrame. 我已经在JFrame的属性窗口中将关闭操作设置为自定义代码。 Whenever I run this JFrame,the custom code executes automatically.Even if I dont close the frame.The custom code is basically a function: 每当我运行此JFrame时,自定义代码都会自动执行。即使我不关闭框架,自定义代码也基本上是一个函数:

public static int logout(){

   int userconfirm=  JOptionPane.showConfirmDialog(null,"Are you sure you want 
             to Exit?","Please Confirm",YES_NO_OPTION);
   if(userconfirm==0){
       return 1;
   }
   else 
      return 0;
   }

I dont know what int value must be returned for closing the frame,I'm just experimenting,so I return a zero or a one. 我不知道关闭框架必须返回什么int值,我只是在做实验,所以我返回零或一。

if(userconfirm==0){

First of all, don't use magic numbers. 首先,不要使用幻数。 People don't know what "0" means. 人们不知道“ 0”是什么意思。 The API provides variables like JOptionPane.YES_OPTION that you can use. API提供了可以使用的变量,例如JOptionPane.YES_OPTION Use the variable provided by the API to make the code more readable. 使用API​​提供的变量使代码更具可读性。

Whenever I run this JFrame,the custom code executes automatically.Even if I dont close the frame 每当我运行此JFrame时,自定义代码都会自动执行。即使我不关闭框架

You should be using a WindowListener to monitor the closing of the window. 您应该使用WindowListener监视窗口的关闭。 The basic logic would be something like: 基本逻辑如下所示:

JFrame frame = new JFrame(...);
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

frame.addWindowListener( new WindowAdapter()
{
    public void windowClosing(WindowEvent e)
    {
        JFrame frame = (JFrame)e.getSource();

        int result = JOptionPane.showConfirmDialog(
            frame,
            "Are you sure you want to exit the application?",
            "Exit Application",
            JOptionPane.YES_NO_OPTION);

        if (result == JOptionPane.YES_OPTION)
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
});

frame.setVisible( true );

Note: there is no need for a method as the closing logic is all handled inside the listener. 注意:不需要方法,因为关闭逻辑都是在侦听器内部处理的。

See Closing an Application for more information and coding ideas. 有关更多信息和编码思路,请参见关闭应用程序

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM