Java Swing How to - Close JFrame using code








Question

We would like to know how to close JFrame using code.

Answer

import javax.swing.JButton;
import javax.swing.JFrame;
//from  ww  w.j  av  a2s.  co m
public class Main {

  public static void main(String[] args) {
    JButton close = new JButton("Close me programmatically");
    final JFrame f = new JFrame("Close Me");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setContentPane(close);
    close.addActionListener(e -> {
      f.dispose();
    });
    f.pack();
    f.setLocationByPlatform(true);
    f.setVisible(true);
  }
}