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);
}
}
Latest posts by Wayan (see all)
- How do I create a string of repeated characters? - September 1, 2023
- How do I convert datetime string with optional part to a date object? - August 28, 2023
- How do I split large excel file into multiple smaller files? - April 15, 2023