-2

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();
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319

1 Answers1

4

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.

Community
  • 1
  • 1
MCMastery
  • 3,099
  • 2
  • 20
  • 43