2012-02-28 88 views
1

我希望窗口关闭,当我按下取消按钮,但它不工作。的Java:取消按钮不会关闭该窗口的JFrame

代码:

public class FirstClass{ 

private JFrame frame; 
private JButton btnCancel; 

public FirstClass() { 

    frame = new JFrame("GRIIS Data Transfer [Mobile to PC]"); 
    frame.setBounds(200,200,900,450); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.getContentPane().setLayout(null); 

    btnCancel = new JButton("Cancel"); 
    btnCancel.setBounds(800, 5, 85, 25); 

    frame.add(btnCancel); 

    btnCancel.addActionListener(new ActionListener() { 

     @Override 
     public void actionPerformed(ActionEvent e) { 
      frame.addWindowListener(new WindowAdapter() { 
       @Override 
       public void windowClosing(WindowEvent e) { 
        super.windowClosing(e); 
        System.exit(0); 
       } 
      }); 
     } 

    }); 

}//end of constructor 
public static void main(String[] args) { 
    EventQueue.invokeLater(new Runnable() { 

     @Override 
     public void run() { 
      try { 
       FirstClass window = new FirstClass(); 
       window.frame.setVisible(true); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } 
    }); 
} 
} 

请让我知道在代码中所需变化的情况下。

btnCancel.addActionListener()

,所以我的代码将工作和关闭应用程序,当我按下取消按钮。

回答

6

不使用窗口听者它在关门时间给事件,尝试

btnCancel.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent e) { 
       System.exit(0); 
      }}); 
+0

感谢名单哥们...... 如果u认为这是好问题,那就请投票吧。 – 2012-02-28 06:10:51

5

无需重写WindowListener的方法,

public void actionPerformed(ActionEvent e) { 
    System.exit(0); 
} 
相关问题