[英]Keeping Track of Every Time that a Checkbox is checked and unchecked
I have most of my java application done already, so I am now logging all user activity. 我已经完成了大部分Java应用程序,因此现在正在记录所有用户活动。 One thing I want to keep track of is whenever one of my checkboxes is checked and unchecked. 我想跟踪的一件事是每当我的复选框之一被选中和未选中时。 I am able to read at the end if the object is checked or unchecked, however I want to know each time the checkbox is used in real time. 我可以在最后阅读该对象是否被选中,但是我想知道每次实时使用复选框。 I want to know how many times the user checks and unchecks the box. 我想知道用户选中和取消选中该框的次数。 Right now I am using something similar to this syntax, but it doesn't print a statement each time the checkbox is checked and unchecked. 现在,我正在使用类似于此语法的内容,但是每次复选框未选中时,它不会打印一条语句。
public CheckboxAction(String text) {
super(text);
}
@Override
public void actionPerformed(ActionEvent event) {
JCheckBox cbLog = (JCheckBox) event.getSource();
if (cbLog.isSelected()) {
System.out.println("Logging is enabled");
} else {
System.out.println("Logging is disabled");
}
}
An ItemListener seems appropriate here ItemListener在这里似乎合适
yourJCheckBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent arg0) {
if (yourJCheckBox.isSelected()) {
// Code to execute when it's selected
}
else {
// Code to execute when not selected
}
}
});
First and foremost, do not override actionPerformed
. 首先,不要覆盖actionPerformed
。 If you need to - at least call super.actionPerformed
before performing your action. 如果需要-至少在执行操作之前调用super.actionPerformed
。 Best way is to use addActionListener
or in this case as @BoDidely mentioned use an addItemListener
. 最好的方法是使用addActionListener
或者在本例中,如@BoDidely所述,使用addItemListener
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.