简体   繁体   中英

Clicking a button to change visibility

I'm trying to set the visibility to false when a button is clicked, but the compiler says "incompatible types". The error occurs where it says if (frame.setVisible(true)) I used JFrame , JButton , JLabel , BorderLayout , ActionEvent , and ActionListener

Object source = event.getSource();

        if (source == changeTextButton)
        {
            if (label.getText().equals(LABEL1))
            {
                label.setText(LABEL2);
            }
            else
            {
                label.setText(LABEL1);
            }
        }  // end of if (source == button)

        if (source == closeButton)
        {
            if (frame.setVisible(true))
            {
                setVisible(false);
            }
        } // end of if (source == closeButton)

frame.setVisible(true) does not return a boolean result, and so cannot be placed inside the test portion of an if block. Please look at the API and you'll see that it is declared as returning void -- nothing -- and so do not put inside that if boolean check.

To restate, per the Java API, the setVisible method signature looks like:

// Window class
public void setVisible(boolean visible)

So again, the method is declared as returning void, and so your code is equivalent to doing:

if (void) {
  // do something
}

Which does not make sense to the compiler since void is neither true nor false.

What you need to use is instead:

if(frame.isVisible()){
fram.setVisible(False);
}

frame.isVisible() returns a boolean (true or false)

You might not even need the if statement and just always do frame.setVisible(false) when closeButton is pressed.

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