我有一个问题数组,一系列可能的答案和一系列我希望通过回答问题找到的属性
String[] questions = new String[]{"Question1", "Question2", "Question3"};
String[] possibleAnswers = new String[]{"yes,no", "yes,no", "big,small"};
String[] properties = new String[]{"", "", ""};
我通过在possibleAnswers数组中的相应元素上使用split来为每个问题和JRadioButtons为该问题创建一个标签。
for (int i = 0; i < questions.length; i++) {
//label that holds the current question
JLabel questionLabel = new JLabel(questions[i]);
questionPanel.add(questionLabel);
// string that holds answers for current question i.e. {yes, no}
String[] currentQuestionAnswers = possibleAnswers[i].split(",");
ButtonGroup buttonGroup = new ButtonGroup();
for (int j = 0; j < currentQuestionAnswers.length; j++) {
JRadioButton btnRadio = new JRadioButton(currentQuestionAnswers[j]);
// action listener that will store the selected answer and the question
btnRadio.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
answer = btnRadio.getText();
// some code that moves answer at the right index in the properties array
}
});
buttonGroup.add(btnRadio);
questionPanel.add(btnRadio);
}
}
这image显示了我想要的样子。
对于每个问题,我想找一个属性。假设{Question1,Question2,Question3}实际上是这些问题{“会谈?”,“昂贵?”,“维度?”}。当我从所选按钮中获取文本时,我将进行会谈 - &gt;是的,昂贵的 - &gt;不,尺寸 - &gt;大,所以属性数组将成为{“是”,“否”,“大”}。
我知道如何获得所选答案,但我无法弄清楚如何找到与该答案相对应的问题。我可以以某种方式使用我创建的按钮组,但我不知道如何。
我希望这是有道理的,有人可以提供帮助。谢谢。
答案 0 :(得分:0)
一种方法是扩展JRadioButton
并添加一个简单的ID字段(标记)。我现在无法测试此代码,但我认为
它应该工作。
class MyRadioButton extends JRadioButton{
private int tag;
public getTag(){ return tag;}
public setTag(int val){ tag = val}
}
然后在actionPerfomed
方法中,只需检查此标记并根据它执行适当的操作。
int tag = 0;
btnRadio.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
answer = btnRadio.getText();
switch(btnRadio.getTag()){
case 0:
//do some action
break;
case 1:
....
}
// some code that moves answer at the right index in the properties array
}
});
btnRadio.setTag(tag++);//this will set a unique tag for each radio button
buttonGroup.add(btnRadio);
或者,如果您不想扩展JRadioButton
,这可能会对您的用例造成过大的影响,您可以使用RadioButton.setActionCommand
和ActionEvent.getActionCommand
btnRadio.setActionCommand("some_unique_string")
然后只需在actionPerformed
if("some_unique_string".equals(ae.getActionCommand())
//do something