简体   繁体   中英

How to close window (Java Swing) after run?

I have standard Swing GUI class:

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;

with init

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

... etc. So we can to close this GUI by standard way:

setDefaultCloseOperation(EXIT_ON_CLOSE);

but how to do the same thing from method? For example:

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

Taken from How to programmatically close a JFrame :

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

When the class extends JFrame , do this instead:

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

When this is executed the JFrame will be closed exactly as if the user pressed the "x" button.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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