Avoid Closing the Form in Java

0
32

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”.

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

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.

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:

Facebook Comments
(Visited 31 times, 1 visits today)

LEAVE A REPLY

Please enter your comment!
Please enter your name here