Java 如何检查 JCheckBox 是否被选中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3599908/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 02:29:19  来源:igfitidea点击:

How to check that a JCheckBox is checked?

javaswingjcheckbox

提问by oneat

How can I check if a JCheckBoxis checked?

如何检查 aJCheckBox是否已选中?

采纳答案by Matthew Flaschen

Use the isSelectedmethod.

使用isSelected方法。

You can also use an ItemListenerso you'll be notified when it's checked or unchecked.

您还可以使用ItemListener,以便在选中或取消选中它时收到通知。

回答by 1ac0

By using itemStateChanged(ItemListener)you can track selecting and deselecting checkbox (and do whatever you want based on it):

通过使用itemStateChanged(ItemListener)您可以跟踪选择和取消选择复选框(并根据它做任何您想做的事情):

myCheckBox.addItemListener(new ItemListener() {
    @Override
    public void itemStateChanged(ItemEvent e) {
        if(e.getStateChange() == ItemEvent.SELECTED) {//checkbox has been selected
            //do something...
        } else {//checkbox has been deselected
            //do something...
        };
    }
});

Java Swing itemStateChanged docushould help too. By using isSelected()method you can just test if actual is checkbox selected:

Java Swing itemStateChanged 文档也应该有所帮助。通过使用isSelected()方法,您可以测试是否选中了实际复选框:

if(myCheckBox.isSelected()){_do_something_if_selected_}