问题描述
如何获取 JCheckbox 的选定索引(从使用 for 循环添加到屏幕的多个 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.
推荐答案
您有一个 JCheckBox 数组,您可以简单地遍历您的数组并找出哪个 JCheckBox 已被选中.
You have an array of JCheckBox, and you can simply iterate through your array and find out which JCheckBox has been selected.
关于:
当我单击复选框时,我想获取所选复选框的索引.
您可以通过使用传递到 ActionListener 的 ActionEvent 的 getSource()
方法找出哪个复选框被选中.例如,您可以将 ActionListener 更改为如下:
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
}
}
}
});
这篇关于如何获取JCheckbox的选定索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!