Avoid Closing the Form in Java

This Tutorial is all about Avoid Closing the Form in Java.
This tutorial entitled “Avoid Closing the Form in Java” will teach you on how to setup a Form in Java that restrict on closing event. The program will restrict the default close operation and avoid the user to close the form.

The program also uses the “window event” to detect the user operation. When the user click the close icon of the form located in the upper right part of the form together with the minimize and maximize icon, a dialog box appear and displaying a text “You cannot close this main form!”. The program uses “JOption Pane” to display a dialog box.

Avoid Closing the Form in Java Steps

Create or add a new form inside your Java source package. Just name the form what you want it to name.

Design your form just look like the image below. In my case, I inserted a Label with a text “YOU CANNOT CLOSE THIS FORM”.

Insert the following codes below inside your “public method”. In Netbeans, the default public method handle the entire form constructor and call the constructor using the method name “initComponents”.

this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter(){
@Override
public void windowClosing(WindowEvent we)
{String ObjButtons[] = {"yes","no"};
int PromptResult = JOptionPane.showConfirmDialog(null, "You cannot close this main form!","Confirmation",JOptionPane.PLAIN_MESSAGE);
if (PromptResult == JOptionPane.CLOSED_OPTION)
{System.exit(0);
}
}
});

 

Run your program and the output should look like the image below.

There are two output displays in the image above; the first image is the display of the actual form when the program is running. The second image display the dialog box displaying the text “You cannot close this main form!”.  Remember that the dialog box will appear when the user clicks the close button.

About The Avoid Closing the Form In Java

Project Name: Avoid Closing the Form
Language/s Used: JAVA
Database: None
Type: Desktop Application
Developer: IT SOURCECODE
Updates: 0
Avoid Closing the Form In Java– Project Information

These features are equipped in some programs especially in the main form part. This feature will forced the user to exit the program using the special logout button so that the program can track all the in and out of the user while using the program. If you have comments and suggestions regarding on this tutorial, feel free to contact us.

Related Articles You May Like:

Leave a Comment