简体   繁体   中英

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.

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

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.

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.

通过复选框迭代并检查isSelected标志

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM