user3479783
user3479783

Reputation: 69

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)

Upvotes: 0

Views: 1064

Answers (2)

Jakkra
Jakkra

Reputation: 651

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.

Upvotes: 2

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285440

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.

Upvotes: 4

Related Questions