Java preventing jframe window from closing
In Java, you can prevent a JFrame
window from closing when the user clicks the close button (the "X" in the top right corner of the window) by overriding the processWindowEvent
method and checking for the WindowEvent.WINDOW_CLOSING
event.
Here's an example:
import javax.swing.JFrame; import java.awt.event.WindowEvent; public class NonClosingFrame extends JFrame { public NonClosingFrame() { super("Non-Closing Frame"); } @Override protected void processWindowEvent(WindowEvent e) { if (e.getID() == WindowEvent.WINDOW_CLOSING) { // Do not allow the window to close return; } super.processWindowEvent(e); } public static void main(String[] args) { NonClosingFrame frame = new NonClosingFrame(); frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); frame.setSize(300, 200); frame.setVisible(true); } }Source:www.theitroad.com
In this example, we override the processWindowEvent
method of the JFrame
to check for the WINDOW_CLOSING
event. If the event is detected, we simply return without calling the superclass's implementation of the method, which would close the window.
To prevent the window from closing, we also set the default close operation to DO_NOTHING_ON_CLOSE
by calling setDefaultCloseOperation
on the frame. This prevents the close button from doing anything when clicked.
When you run this example, a window will appear with a title bar and close button. If you click the close button, nothing will happen and the window will remain open.