How To prevent other JFrame forms from closing when one form is closed

How To prevent other JFrame forms from closing when one form is closed

To prevent other JFrame forms from closing when one form is closed, you can do the following:

  1. When creating the other JFrame forms, set their default close operation to HIDE_ON_CLOSE using the setDefaultCloseOperation method. This will cause the form to be hidden when the close button is clicked, rather than being closed and disposed.
otherFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
  1. In the action listener for the close button of the main form, call the dispose method on the main form to close it, but do not call the dispose method on the other forms. This will allow them to remain open.
mainFrame.dispose();

Alternatively, you can also use a modal dialog to display the other forms, which will prevent the user from interacting with the main form until the dialog is closed.

Here is an example of two forms in Java Swing, where the first form has a button that opens the second form when clicked:

Form 1 (MainForm.java):

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
/**
 *
 * @author HP
 */


public class MainForm extends JFrame {

    public MainForm() {
        setSize(400, 300);
        setTitle("Main Form");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JButton btnOpenOtherForm = new JButton("Open Other Form");
        btnOpenOtherForm.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // Open the second form when the button is clicked
                OtherForm otherForm = new OtherForm();
                otherForm.setVisible(true);
            }
        });
        add(btnOpenOtherForm);
    }

    public static void main(String[] args) {
        MainForm mainForm = new MainForm();
        mainForm.setVisible(true);
    }
}

Form 2 (OtherForm.java):




import javax.swing.JFrame;

public class OtherForm extends JFrame {

    public OtherForm() {
        setSize(400, 300);
        setTitle("Other Form");
        setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
    }
}

To test these forms, you can create two separate Java files for each form, then run the main method of the MainForm class to start the application.

READ MORE  C SHARP AND MYSQL DATABASE CRUD TUTORIAL 50 How To clear Or Reset Check Box On Button Click

You can Clone The Code From This Github Repository Link – https://github.com/mauricemuteti/How-To-prevent-other-JFrame-forms-from-closing-when-one-form-is-closed.git

Leave a Reply

Your email address will not be published. Required fields are marked *