关闭JFrame =>程序崩溃

时间:2015-02-18 16:12:05

标签: java swing jframe

我有两个JFrame s:

  • ApplicationsJFrame,这是我的主要内容,
  • InsertApplicationsForm

点击InsertApplicationsForm中的Button,我可以看到ApplicationsJFrame

每次关闭InsertApplicationsForm时,ApplicationsJFrame也会关闭,但程序仍在运行,当我最小化InsertApplicationsForm时,ApplicationsJFrame最小化,但不会最大化......

ApplicationsJFrame:

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("T-AMS");
setFocusableWindowState(false);

InsertApplicationsForm:

public class InsertApplicationForm extends javax.swing.JFrame {

    /**
     * Creates new form InsertApplicationForm
     */
    public InsertApplicationForm() {
        initComponents();
    }

[...]

setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Insert Application")
addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

private void formWindowClosed(java.awt.event.WindowEvent evt) {                                  
        ApplicationsJFrame.insert = false;
    }

打开InsertApplicationsForm

new InsertApplicationForm().setVisible(true);

1 个答案:

答案 0 :(得分:0)

您应该将EXIT_ON_CLOSE常量int添加到主JFrame中。 而是将WindowListener添加到时间帧:

//Suppose you have a custom Frame in your Form class
class InsertApplicationsForm extends JFrame{
//Some stuff
//...

public InsertApplicationsForm(){
//Implement
    //DO NOT ADD setDefaultCloseOperation
setVisible(true);
}

addWindowListener(new WindowAdapter(){

     @Override
    public void windowClosing(WindowEvent e){
        InsertApplicationsForm.this.dispose();
    }

});

}

所以在你的主要类或方法,事件中,无论如何调用它:

new InsertApplicationsForm();

并会自动打开一个新的JFrame,您可以关闭它,而不会影响主框架或其他框架。你甚至可以实例化这个类的多个帧,关闭不会影响其他类。