How to disable close button on a JFrame in Java?

To disable the close button, let us first create a frame −

JFrame frame = new JFrame("Login!");

Use the setDefaultCloseOperation() to set the status of the close button. Set it to DO_NOTHING_ON_CLOSE to disable it −


The following is an example to disable close button on a JFrame in Java −


package my;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public class SwingDemo {
   public static void main(String[] args) throws Exception {
      JFrame frame = new JFrame("Login!");
      JLabel label1, label2, label3;
      frame.setLayout(new GridLayout(2, 2));
      label1 = new JLabel("DeptId", SwingConstants.CENTER);
      label2 = new JLabel("SSN", SwingConstants.CENTER);
      label3 = new JLabel("Password", SwingConstants.CENTER);
      JTextField deptid = new JTextField(20);
      JTextField ssn = new JTextField(20);
      JPasswordField passwd = new JPasswordField();
      frame.add(label1); frame.add(label2); frame.add(label3); frame.add(deptid); frame.add(ssn); frame.add(passwd);
      frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); frame.setSize(550, 400);

The output is as follows displaying the close button but it won’t work since we disabled it above −


Updated on: 30-Jul-2019


Kickstart Your Career

Get certified by completing the course

Get Started