简体   繁体   中英

Can't change/modify button background from another method - JAVA

I have a problem about modify button background. I am using netbeans gui builder for build form. I am trying change button background when the second frame is open and turn it back when second frame close.

public void update(boolean x){
    if(x==true){
        circleButton.setOpaque(true);
        circleButton.setBackground(new java.awt.Color(0, 0, 0));

        System.out.println("testoutput");
    }
}

this is my update method from first class.

I added window listener to second frame.

private void formWindowOpened(java.awt.event.WindowEvent evt) {                                  
    isitopen = true;
    //this is first class which includes button
    homework hwork = new homework();

    hwork.update(isitopen);

    System.out.println("testoutput2");
}

I got 2 testoutput but color of the button didn't change.

What can i do to fix this issue ?

You're creating a new homework object in your formWindowOpened(...) method, one completely unrelated to the homework object that is displayed, and changing the state of the new object will have no effect on the displayed one.

A simple and WRONG solution is to use static fields or methods.

Instead one simple solution is to give the calss with your formWindowOpened(...) method a valid reference to the displayed homework object, something that can be done with a constructor parameter or a setHomework(...) method.

A much better and even simpler solution:

  • Make the 2nd window a modal JDialog, not a JFrame
  • This way homework will know when the window is open and can set its own button colors. When the 2nd window opens, program flow in the calling class is put on hold, and only resumes when the 2nd window closes -- just like using a JOptionPane.

For more on this, please see The Use of Multiple JFrames, Good/Bad Practice?

As an aside, you will want to learn and use Java naming conventions . Variable names should all begin with a lower letter while class names with an upper case letter. Learning this and following this will allow us to better understand your code, and would allow you to better understand the code of others.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM