I have a checkbox on a JFrame. When I check it, I want to display on the command window that it has been selected. Below is the code i am working with. It compiles and executes without errors, but I don't get the "one has been selected" on the window when I select the checkbox.
public Checklist() {
...
JCheckBox one = new JCheckBox("CT scan performed");
one.addItemListener(new CheckBoxListener());
}
private class CheckBoxListener implements ItemListener{
public void itemStateChanged(ItemEvent e)
{
if(e.getSource()==one){ if(one.isSelected()){
System.out.println("one has been selected");
}
else{System.out.println("nothing");}
}
}}
I have tested this simple example and it works perfectly (it writes "one has been selected"
when you select the checkbox, and "nothing"
when you deselect it):
import javax.swing.*;
import java.awt.event.*;
public class Example extends JFrame{
public JCheckBox one;
public Example() {
one = new JCheckBox("CT scan performed");
one.addItemListener(new CheckBoxListener());
setSize(300,300);
getContentPane().add(one);
setVisible(true);
}
private class CheckBoxListener implements ItemListener{
public void itemStateChanged(ItemEvent e) {
if(e.getSource()==one){
if(one.isSelected()) {
System.out.println("one has been selected");
} else {System.out.println("nothing");}
}
}
}
public static void main(String[] args) {
new Example();
}
}
In your example, it seems that one
is declared in the constructor CheckList()
. Are you sure that it can be accessed in the inner class CheckBoxListener
?