我正在尝试编写一个方法,使用简单的if语句将按钮从禁用切换为启用并返回。
我认为它会像
if (buttonDisable.setEnabled(true) == true){
//do stuff
}
但是我没有太多运气通过谷歌找到答案。
答案 0 :(得分:4)
为什么不一次切换状态:
buttonDisable.setEnabled(!buttonDisable.isEnabled())
答案 1 :(得分:4)
不要测试模型的显示,测试模型。
if (buttonDisable.getModel().isEnabled()) {
// do stuff
}
这样一来,如果你改变模型,你就会避免一定程度的调度(视图---更新--->模型---更新--->视图)
更好的解决方案是使模型更改独立于视图。通过这种方式,您无需担心需要使用特定视图来进行模型更改。
ButtonModel toggle = new ButtonModel();
...
JButton button = new JButton(toggle);
...
// this is clear that we are manipulating the model, not the view
// as new views are added / removed, this toggle will continue to work
toggle.setEnabled(!toggle.isEnabled());