learner
learner

Reputation: 331

How to get the selected index of JCheckbox?

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.

Upvotes: 3

Views: 3748

Answers (4)

Derek W
Derek W

Reputation: 10026

I would try something like:

for (int i=0; i < checkBoxes.length; i++) {
if (checkBoxes[i].isSelected() == true) {
index = i; }
return index; }

From your question, this is what I gather that you are looking for.

EDIT:

My above previous method is flawed because it makes the very naive approach that one and only one box will be selected and that no box will be deselected.

Where 'e' is the ActionEvent object,

for (int i=0; i < checkBoxes.length; i++) {
if (checkBoxes[i] == e.getSource()) {
index = i; } }
return index; 

This way the most recent selection or deselection check box is identified.

Upvotes: 0

Dimochka
Dimochka

Reputation: 301

As far as I understand, you want to get the index of a selected JCheckBox in order to respond appropriately on a user's action.

If this is the case, you might want to consider a different approach: you can register an ItemListener for each of your checkboxes.

JCheckBox check = new JCheckBox("Approve");
check.addItemListener(new ItemListener() {
  public void itemStateChanged(ItemEvent e) {
    if (check.isSelected()){
      System.out.println(check.getName() + " is selected");
    }
  }
});

(inspired by java2s.com tutorial)

In this case the event will be fired immediately and you will always know which checkbox was just clicked.

Upvotes: 1

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

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
      }
    }
  }
});

Upvotes: 4

CloudyMarble
CloudyMarble

Reputation: 37566

Iterate throuh the Checkboxes and check the isSelected flag

Upvotes: 0

Related Questions