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 handle cookies using Jakarta Servlet API? - April 19, 2025
- How do I set response headers with HttpServletResponse? - April 18, 2025
- How do I apply gain and balance using FloatControl? - April 18, 2025