Java Swing How to - Minimize the window and not to close it when the user click on the "x" button








Question

We would like to know how to minimize the window and not to close it when the user click on the "x" button.

Answer

//from  ww w.j  a  v a2 s . com
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

import javax.swing.JFrame;

public class Main {
  public static void main(String[] args) throws Exception {
    Main s = new Main();
    s.start();
  }
  JFrame frame;
  public void start() {
    frame = new JFrame();
    frame.setSize(400, 400);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    frame.addWindowListener(new myWindowListener());
  }

  class myWindowListener implements WindowListener {
    public void windowClosing(WindowEvent e) {
      frame.setState(JFrame.ICONIFIED);
    }

    public void windowActivated(WindowEvent e) {
    }

    public void windowClosed(WindowEvent e) {
    }

    public void windowDeactivated(WindowEvent e) {
    }

    public void windowDeiconified(WindowEvent e) {
    }

    public void windowIconified(WindowEvent e) {
    }

    public void windowOpened(WindowEvent e) {
    }
  }
}