I am using Java and Swing, all I want to de is to test if the Jcheckbox is selected and if so adding its text to a list of Strings, the problem is that the isSelected fuction is always returning False even if the checkbox is selected. Here is the code I wrote:
List<JCheckBox> checkBoxes = new ArrayList<JCheckBox>();
List<String> infos = new ArrayList<String>();
String sql = "select NAME from drugs ";
pre=con.prepareStatement(sql);
res=pre.executeQuery();
while(res.next()){
checkBoxes.add(new JCheckBox(res.getString("NAME")));
panel.add(new JCheckBox(res.getString("NAME")));
};
for (JCheckBox checkBox : checkBoxes) {
if (checkBox.isSelected()) {
infos.add(checkBox.getText());
}
}
Code in Java runs once through unless you write code in a loop. You're checking if the checkbox is selected instantly after they are created in the panel. The code is checking if your newly added check boxes are selected (which of course no one has clicked them yet) and then finishes. They are never checked again.
The solution will be to move this selection check into an event handler. But before we get there, you have a second error in your code.
while(res.next()){
checkBoxes.add(new JCheckBox(res.getString("NAME")));
panel.add(new JCheckBox(res.getString("NAME")));
};
The checkbox you add to your checkBoxes data structure and the checkbox you add to the panel are two different check boxes. Each time you use the new keyword in Java, you create a new independent object. In your case what you really need is to create 1 new checkbox, and put it in the panel, and also store it in your data structure.
The solution:
while(res.next()){
JCheckBox checkBox = new JCheckBox(res.getString("NAME"));
checkBoxes.add(checkBox);
panel.add(checkBox);
};
Now we can continue to create an event handler. An event handler will react to someone clicking the check box and run the code that checks the state of the check box to apply any changes. An event handler example to suit your needs can be coded as follows:
checkBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
infos.add(checkBox.getText());
}
if (e.getStateChange() == ItemEvent.DESELECTED) {
infos.remove(checkBox.getText());
}
}
});
Now when we join the code with all the fixes we get:
while(res.next()){
JCheckBox checkBox = new JCheckBox(res.getString("NAME"));
checkBoxes.add(checkBox);
panel.add(checkBox);
checkBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
infos.add(checkBox.getText());
}
if (e.getStateChange() == ItemEvent.DESELECTED) {
infos.remove(checkBox.getText());
}
}
});
}