更新时间:2023-11-25 15:02:40
您可以在每个上使用 setActionCommand( + j)
按钮,将每个按钮与其索引相关联,然后使用 bg.getSelection()。getActionCommand()
获取任意组中所选按钮的索引。然后,您可以将一个ActionListener分配给一个组中的所有按钮,并确保操作侦听器知道它附加到了哪一行。
You could use setActionCommand("" + j)
on each button to associate each button with its index, and then get the selected button's index in any group with bg.getSelection().getActionCommand()
. You can then assign a single ActionListener to all the buttons in one group, and make sure the action listener knows which row it's attached to.
// in your "i" loop
final int row = i; // must be final to be used inside the anonymous class
final ButtonGroup btnG = bg;
final String answerAction = "" + ranNumber; // hard to tell if this is what you mean
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("row " + row);
String selectedAction = btnG.getSelection().getActionCommand();
System.out.println("btn " + selection);
boolean isCorrectForThisRow = (answerAction == selectedAction);
System.out.println("is correct: " + isCorrectForThisRow);
}
};
// in your "j" loop, with either the answerLetter or k buttons
// as required
k.setActionCommand("" + j);
k.addActionListener(listener);
就目前而言,您的样本中有很多内容并不太有意义,因此很难提出更多建议(例如, while(true)
循环在第一次迭代时就中断了)。但是应该使用 setActionCommand
(此处的Oracle教程),以这种方式找出在按钮组中选中了哪个按钮。
As it stands, there is a lot to your sample that doesn't quite make sense, so it's hard to suggest more than this (for example - a while(true)
loop that breaks on it's first iteration). But setActionCommand
is meant to be used (oracle tutorial here) in exactly this way to find out which button is checked in a button group.