Search code examples
javaswingjframemultiple-instancesjcheckbox

How to Remember Checkbox Checked From Other Frame


I have two jframe, one is a main frame used to call check box frame, and another one is a jframe containing checkbox.

MainFrame.java

enter image description here

How to remember previous checked checkbox after main frame call again the checkbox frame?

CheckBox.java

enter image description here

below is my button action code:

private void btn_callCheckBoxActionPerformed(
  java.awt.event.ActionEvent evt) {                                         

    //call checkbox window
    CheckBoxWindow cbw = new CheckBoxWindow();
    cbw.setVisible(true);
    cbw.setEnabled(true);

    this.setVisible(true);
    this.setEnabled(false);

}    

call mainframe from checkbox frame

private void btn_callMainFrameActionPerformed(
  java.awt.event.ActionEvent evt) {                                         

    //call main frame window
    MainPage mp = new MainPage();
    mp.setVisible(true);
    mp.setEnabled(true);
    this.setEnabled(false);
    this.setVisible(false);
}

Solution

  • you have multiple options.

    1- Do not create new windows every time you click the buttons. Save the windows in variables and use setVisible(true) and setVisible(false) to show/hide them. If you hide the checkbox frame and the you show it again, the checkbox will be in the state before closing.

    This something like this

     public MainPage() {
         this.checkWindow = new CheckWindow()
     }
    
     private void btn_callCheckBoxActionPerformed(java.awt.event.ActionEvent evt)  {                                         
            // show window
            this.checkWindow.setVisible(true);
            this.checkWindow.setEnabled(true);
    
            this.setVisible(true);
            this.setEnabled(false);
      }  
    

    2.- Save and retrieve the values of the checkbox using the preferences api of java