Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/388.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Java中,在窗口关闭时,在哪里放置可靠启动的代码?_Java_Swing - Fatal编程技术网

在Java中,在窗口关闭时,在哪里放置可靠启动的代码?

在Java中,在窗口关闭时,在哪里放置可靠启动的代码?,java,swing,Java,Swing,在用户采取关闭窗口的操作(通过标题栏中的按钮、菜单项或我提供的按钮)之后以及在处理之前,我有几个要保存默认值的窗口 有些窗口我可以在关闭时处置,但有些窗口在处置前需要信息() 似乎只有当窗户被处理掉的时候才会着火,我不能总是依赖它(见上下) 似乎只有当用户从标题栏的系统菜单关闭窗口时才会触发,即使我在自己的菜单操作处理程序中调用system.exit(0) 根据do GC文档,dispose()方法并不总是被调用,并且在应用程序关闭时经常被忽略 我必须运行System.runFinalizat

在用户采取关闭窗口的操作(通过标题栏中的按钮、菜单项或我提供的按钮)之后以及在处理之前,我有几个要保存默认值的窗口

  • 有些窗口我可以在关闭时处置,但有些窗口在处置前需要信息()
  • 似乎只有当窗户被处理掉的时候才会着火,我不能总是依赖它(见上下)
  • 似乎只有当用户从标题栏的系统菜单关闭窗口时才会触发,即使我在自己的菜单操作处理程序中调用system.exit(0)
  • 根据do GC文档,dispose()方法并不总是被调用,并且在应用程序关闭时经常被忽略
  • 我必须运行System.runFinalization(),但代码仍然没有执行。无论如何,这可能太晚了,因为到那时一些窗户已经被处理掉了

如何确保在释放窗口之前运行代码?这是一个窗口应该能够自行处理的任务。关闭、关闭和处置事件的不可靠性让我有点沮丧。我缺少什么?

使用方法。一般来说,在Java中,您不能依赖配置。不能保证调用此方法。

在这里找到许多类似问题后:

我创建了一个应用程序,在
windowDeactivated
windowClosing
windowClosing
事件中的每个事件上触发
System.out.println()
语句,并尝试使用System X按钮和刚刚设置可见的按钮关闭
JFrame
JDialog
窗口(false):


将其作为windowlistener添加到JDialog或JFrame扩展中,并实现CloseDuctions版本,为关闭窗口的业务增加了极大的灵活性和可靠性。

刚刚找到了我自己问题的答案:Rob Camick编写了一个函数,提供了两个涵盖所有基础的侦听器类。您可以。另请参见。这与我原来帖子中的第二点有什么不同?如果我提供自己的按钮或菜单项,windowClosed()将不会启动。您使用了一个有趣的名称来调用它(即使链接出现在右侧),所以我错过了它。通常-使用所有方法,因为它们在不同的事件(如Closed和Closed)上触发。另外,我可以建议您在每个方法中添加日志记录吗?它可能太快了,你可能会错过它。
/**
* Test program to explore the relationship between defaultCloseOperation 
* states, and the sequence of events triggered when closing a window 
* with the (X) button vs using setVisible(false).
* 
* @author MaskedCoder
*
*/

package testwindowadapter;

import java.awt.EventQueue;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.WindowConstants;

/**
* Class to listen for window close events
*/
public class WindowNotifier extends WindowAdapter implements WindowListener
{
    public WindowNotifier() {
        super();
    }

    @Override
    public void windowClosing(WindowEvent e)
    {
        super.windowClosing(e);
        System.out.println(e.getComponent().getClass().getSimpleName() + ".windowClosing fired");
    }

    @Override
    public void windowClosed(WindowEvent e) {
        super.windowClosed(e); //To change body of generated methods, choose Tools | Templates.
        System.out.println(e.getComponent().getClass().getSimpleName() + ".windowClosed fired");
    }

    @Override
    public void windowDeactivated(WindowEvent e) {
        super.windowDeactivated(e); 
        System.out.println(e.getComponent().getClass().getSimpleName() + ".windowDeactivated fired");
    }
}

/**
* Creates new form TestDialog
*/
public class TestDialog extends javax.swing.JDialog {

    public TestDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        addWindowListener(new WindowNotifier());
        cboDefaultCloseOp.setSelectedIndex(getDefaultCloseOperation());
    }

    /**
    * This method is called from within the constructor to initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is always
    * regenerated by the Form Editor.
    */
    @SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    btnClose = new javax.swing.JButton();
    cboDefaultCloseOp = new javax.swing.JComboBox();

    setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
    setTitle("WindowAdapter Test");

    btnClose.setText("Close window");
    btnClose.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
        btnCloseActionPerformed(evt);
    }
    });

    cboDefaultCloseOp.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "DO_NOTHING_ON_CLOSE", "HIDE_ON_CLOSE", "DISPOSE_ON_CLOSE" }));
    cboDefaultCloseOp.addItemListener(new java.awt.event.ItemListener() {
    public void itemStateChanged(java.awt.event.ItemEvent evt) {
        cboDefaultCloseOpItemStateChanged(evt);
    }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(cboDefaultCloseOp, javax.swing.GroupLayout.PREFERRED_SIZE, 225, javax.swing.GroupLayout.PREFERRED_SIZE))
        .addGroup(layout.createSequentialGroup()
            .addGap(58, 58, 58)
            .addComponent(btnClose)))
        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
        .addContainerGap()
        .addComponent(cboDefaultCloseOp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addGap(18, 18, 18)
        .addComponent(btnClose)
        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );

    pack();
}// </editor-fold>                        

private void btnCloseActionPerformed(java.awt.event.ActionEvent evt) {                                         
    setVisible(false);
}                                        

private void cboDefaultCloseOpItemStateChanged(java.awt.event.ItemEvent evt) {                                                   
    setDefaultCloseOperation(cboDefaultCloseOp.getSelectedIndex());
}                                                  

// Variables declaration - do not modify                     
private javax.swing.JButton btnClose;
private javax.swing.JComboBox cboDefaultCloseOp;
// End of variables declaration                   
}

/**
* Creates new form TestFrame
*/
public class TestFrame extends javax.swing.JFrame {

    public TestFrame() {
        super();
        initComponents();
        addWindowListener(new WindowNotifier());
        cboDefaultCloseOp.setSelectedIndex(getDefaultCloseOperation());
    }

    /**
    * This method is called from within the constructor to initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is always
    * regenerated by the Form Editor.
    */
    @SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    cboDefaultCloseOp = new javax.swing.JComboBox();
    btnClose = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    cboDefaultCloseOp.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "DO_NOTHING_ON_CLOSE", "HIDE_ON_CLOSE", "DISPOSE_ON_CLOSE", "EXIT_ON_CLOSE" }));
    cboDefaultCloseOp.addItemListener(new java.awt.event.ItemListener() {
    public void itemStateChanged(java.awt.event.ItemEvent evt) {
        cboDefaultCloseOpItemStateChanged(evt);
    }
    });

    btnClose.setText("Close window");
    btnClose.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
        btnCloseActionPerformed(evt);
    }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(cboDefaultCloseOp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        .addGroup(layout.createSequentialGroup()
            .addGap(41, 41, 41)
            .addComponent(btnClose)))
        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
        .addContainerGap()
        .addComponent(cboDefaultCloseOp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addGap(18, 18, 18)
        .addComponent(btnClose)
        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );

    pack();
}// </editor-fold>                        

private void btnCloseActionPerformed(java.awt.event.ActionEvent evt) {                                         
    setVisible(false);
}                                        

private void cboDefaultCloseOpItemStateChanged(java.awt.event.ItemEvent evt) {                                                   
    setDefaultCloseOperation(cboDefaultCloseOp.getSelectedIndex());
}                                                  

// Variables declaration - do not modify                     
private javax.swing.JButton btnClose;
private javax.swing.JComboBox cboDefaultCloseOp;
// End of variables declaration                   
}

public class TestWindowAdapter {

    public TestWindowAdapter() {

    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
//              TestDialog MainWin = new TestDialog(null, true);
                TestFrame MainWin = new TestFrame();
                MainWin.setVisible(true);
            }
        });
    }

}
/**
 *
 * @author MaskedCoder
 */
package testwindowadapter;

import java.awt.Window;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.WindowConstants;

public class ReliableOneShotCloseListener extends WindowAdapter implements WindowListener {
    public interface CloseDuties {
        public boolean confirmClose(WindowEvent e);
        public void windowClosing(WindowEvent e);
    }

    private CloseDuties closeDuties;
    private int defaultCloseOperation;
    private boolean windowClosingFired = false;

    public ReliableOneShotCloseListener(int iniDefaultCloseOperation, CloseDuties iniCloseDuties) {
        super();
        closeDuties = iniCloseDuties;
        defaultCloseOperation = iniDefaultCloseOperation;
    }

    private int getDefaultCloseOperation(WindowEvent e) {
        if(e.getComponent() instanceof JFrame) {
            return ((JFrame) e.getComponent()).getDefaultCloseOperation();
        } 
        else if(e.getComponent() instanceof JDialog) {
            return ((JDialog) e.getComponent()).getDefaultCloseOperation();
        }
        else throw new IllegalArgumentException("WindowEvent.getComponent() is " + e.getComponent().getClass().getSimpleName() + ", must be JFrame or JDialog.");
    }

    private void setDefaultCloseOperation(WindowEvent e, int newDefaultCloseOperation) {
        if(e.getComponent() instanceof JFrame) {
            ((JFrame) e.getComponent()).setDefaultCloseOperation(newDefaultCloseOperation);
        } 
        else if(e.getComponent() instanceof JDialog) {
            ((JDialog) e.getComponent()).setDefaultCloseOperation(newDefaultCloseOperation);
        }
        else throw new IllegalArgumentException("WindowEvent.getComponent() is " + e.getComponent().getClass().getSimpleName() + ", must be JFrame or JDialog.");
    }

    private void performCloseDuties(WindowEvent e) {
        if(!windowClosingFired) {
            if(closeDuties.confirmClose(e)) {
                setDefaultCloseOperation(e, defaultCloseOperation);
                closeDuties.windowClosing(e);
                windowClosingFired = true;
            }
            else
                setDefaultCloseOperation(e, WindowConstants.DO_NOTHING_ON_CLOSE);
        }
    }

    public int getDefaultCloseOperation() {
        return defaultCloseOperation;
    }

    public void setDefaultCloseOperation(int newDefaultCloseOperation) {
        defaultCloseOperation = newDefaultCloseOperation;
    }

    @Override
    public void windowOpened(WindowEvent e) {
        windowClosingFired = false;
    }

    @Override
    public void windowClosing(WindowEvent e) {
        performCloseDuties(e);
    }

    @Override
    public void windowClosed(WindowEvent e) {
        performCloseDuties(e);
    }

    @Override
    public void windowActivated(WindowEvent e) {
        windowClosingFired = false;
    }

    @Override
    public void windowDeactivated(WindowEvent e) {      
        if(!e.getComponent().isVisible()) 
            performCloseDuties(e);
    }
}