How to disable main JFrame when open new JFrame, Dispose and System.exit(0)

You must understand the concept of Dispose and exit in java Swing Application. Let us just assume that you have multiple JFrames and JDialog’s in you Java Project and while using them you just want to close the current running JFrame or JDialog.

What is a good Practice to design an application, if you suggest me it is better to use as many as JDialog but not JFrames. Working with Multiple JFrames is always a bad practice.

Why Using Multiple JFrames is a Bad Practice.

I will give u a simple example with my working experience with JFrames and JDialogs.

JFrame always behave as Parent for all the JDialog, assuming that JFrame is Parent and JDialog is Child of the JFrameJFrame can open a JDialog with restricting another JDialog until it is closed.

But if you open a JFrame on another JFrame it is not possible to disable the main frame.

setModalityType(ModalityType.APPLICATION_MODAL);

 

Note: the above line of code must be written in your JDialog constructor but not in your JFrame. Simply writing the code will restrict the other frames to open unless the current JFrame is closed.

Now you must understand the concept of

dispose();

System.exit(0);

 

There are two ways to use those above methods.

Let’s assume you are creating an application which contain multiple JFrame’s and JDialog’s.

You can call the method dispose() to close only current JDialog on button click so that the current frame get closed.

    JButton btnClose = new JButton("close");
    btnClose.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent arg0) {
        dispose();
    // it is best practice to call dispose() method for JDialog



      }
    });
    btnClose.setBounds(29, 432, 89, 23);
    getContentPane().add(btnClose);

 

When it come to JFrame closing on a action performed you can call the System.exit(0). This code will exit the complete running process of the application.

    JButton btnClose = new JButton("exit");
    btnClose.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent arg0) {
        System.exit(0);
    // it is best practice to call System.exit(0); method for JFrames
      }
    });
    btnClose.setBounds(29, 432, 89, 23);
    getContentPane().add(btnClose);

In the above code you can see that we called the System.exit(0) which closes the entire application process so that you must start the application from the beginning of the time.

intactabode