JFrame default close behavior - Java Swing

Java examples for Swing:JFrame

Introduction

You can set the JFrame default close behavior by using one of the four constants in its setDefaultCloseOperation() method.


// Exit the application when the JFrame is closed
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

The other options are:

  • DO_NOTHING_ON_CLOSE
  • HIDE_ON_CLOSE
  • DISPOSE_ON_CLOSE
  • EXIT_ON_CLOSE

Example.

Demo Code

import javax.swing.JFrame;

public class Main {
  public static void main(String[] args) {
    // Create a frame
    JFrame frame = new JFrame("Revised Simplest Swing");

    // Set the default close behavior to exit the application
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // Set the x, y, width and height properties in one go
    frame.setBounds(50, 50, 200, 200);//from   w  w  w.  j a v a2  s .c  o  m

    // Display the frame
    frame.setVisible(true);
  }
}

Related Tutorials