单击按钮以更改可见性
问题描述:
我试图将单击按钮时可见性设置为false,但编译器显示“不兼容的类型”。那里说if (frame.setVisible(true))
我用JFrame
,JButton
,JLabel
,BorderLayout
,ActionEvent
,并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)
不返回布尔值结果,因此不能放在一个如果块的测试部分内发生的错误。请看看API,你会发现它被声明为返回void
- 什么都没有 - 所以如果布尔检查的话,不要把它放在里面。
要重申,按照Java的API,该setVisible
方法签名的样子:
// Window class
public void setVisible(boolean visible)
如此反复,该方法被声明为返回void,所以你的代码就相当于做:
if (void) {
// do something
}
这对编译器没有意义,因为void既不是真也是false。
答
你需要使用什么来代替:
if(frame.isVisible()){
fram.setVisible(False);
}
frame.isVisible() returns a boolean (true or false)
你可能甚至不需要if statement
,只是始终做到frame.setVisible(false)
当按下closeButton
。
哪条线给你错误? –
“if(frame.setVisible(true))” – user3479783
而且,问题在于此语句不是有效的Java。你实际上陈述了“if(void)”,这是没有意义的。 –