How do I disable JFrame close button?

To disable the close operation on a JFrame, when user click the close icon on the JFrame, we can set the value of the default close operation to WindowConstants.DO_NOTHING_ON_CLOSE.

package org.kodejava.swing;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.HeadlessException;

public class DisableCloseButtonDemo extends JFrame {
    public DisableCloseButtonDemo() throws HeadlessException {
        initialize();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new DisableCloseButtonDemo().setVisible(true));
    }

    private void initialize() {
        // WindowConstants.DO_NOTHING_ON_CLOSE tell JFrame instance to do
        // nothing when a window closing event occurs.
        this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);

        JButton button = new JButton("Close");
        button.addActionListener(e -> System.exit(0));

        this.setLayout(new FlowLayout(FlowLayout.CENTER));
        this.setSize(new Dimension(500, 500));
        this.getContentPane().add(button);
    }
}
Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.