如何在运行后关闭窗口(Java Swing)?

时间:2015-07-04 23:45:40

标签: java swing

我有标准的Swing GUI类:

public class ElevatorGUI extends JFrame implements Observer {
private JButton button2;
private JTextArea textArea2;
private JSeparator separator2;
private JLabel label4;
private JLabel label5;
private JLabel label6;

使用init

Container contentPane = getContentPane();
GroupLayout contentPaneLayout = new GroupLayout(contentPane);
    contentPane.setLayout(contentPaneLayout);
    contentPaneLayout.setHorizontalGroup(
        contentPaneLayout.createParallelGroup()
            .addGroup(contentPaneLayout.createSequentialGroup()

...等 所以我们可以通过标准方式关闭这个GUI:

setDefaultCloseOperation(EXIT_ON_CLOSE);

但如何从方法做同样的事情? 例如:

public void update() {
Thread.currentThread().interrupt();
}

1 个答案:

答案 0 :(得分:3)

取自How to programmatically close a JFrame

  

frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));

当课程延伸JFrame时,请改为:

  

this.dispatchEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));

执行此操作时,JFrame将完全关闭,就像用户按下" x"按钮。