Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the selected index of JCheckbox?

Tags:

java

swing

How to get the selected index (from a number of jcheckbox added to the screen using for loop) of JCheckbox?.

// for some t values:
checkBoxes[t] = new JCheckBox("Approve");
checkBoxes[t].addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent  e) {
        boolean selected = checkBoxes[t].isSelected();
        System.out.println("Approved"+selected);
    }
});

When i click the check box, i want to get the selected check box's index.

like image 272
learner Avatar asked Jan 28 '26 10:01

learner


1 Answers

You have an array of JCheckBox, and you can simply iterate through your array and find out which JCheckBox has been selected.

Regarding:

When i click the check box, i want to get the selected check box's index.

Edit: You would find out which checkbox was selected by using the getSource() method of the ActionEvent passed into the ActionListener. For example you could change your ActionListener to as follows:

checkBoxes[t].addActionListener(new ActionListener() {
  public void actionPerformed(ActionEvent  e) {
    boolean selected = checkBoxes[t].isSelected();
    System.out.println("Approved"+selected);

    int index = -1;
    for (int i = 0; i < checkBoxes.length; i++) {
      if (checkBoxes[i] == e.getSource()) {
        index = i;
        // do something with i here
      }
    }
  }
});
like image 156
Hovercraft Full Of Eels Avatar answered Jan 31 '26 00:01

Hovercraft Full Of Eels