public Quiz(){
frame = new JFrame();
frame.setSize(500, 500);
frame.setLocationRelativeTo(null);
frame.setTitle("x");
frame.getContentPane().setBackground(Color.GRAY);
frame.setLayout(new FlowLayout());
label = new JLabel("What is...?");
frame.add(label);
choiceA = new JRadioButton("A", true);
//this if statement happens even if I click on one of the other radio buttons and if I leave this one set to false then none of the events happen
choiceB = new JRadioButton("B");
choiceC = new JRadioButton("C");
choiceD = new JRadioButton("D");
frame.add(choiceA);
frame.add(choiceB);
frame.add(choiceC);
frame.add(choiceD);
group = new ButtonGroup();
group.add(choiceA);
group.add(choiceB);
group.add(choiceC);
group.add(choiceD);
checkButton = new JButton("Check");
frame.add(checkButton);
Handler handler = new Handler();
checkButton.addActionListener(handler);
choiceA.addActionListener(handler);
choiceB.addActionListener(handler);
choiceC.addActionListener(handler);
choiceD.addActionListener(handler);
}
public static void main (String args[]){
Quiz quiz = new Quiz();
quiz.frame.setResizable(false);
quiz.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
quiz.frame.setVisible(true);
}
private class Handler implements ActionListener{
public void actionPerformed(ActionEvent event){
checkButtonActionPerformed(event);
}
public void checkButtonActionPerformed(ActionEvent event){
Quiz quiz = new Quiz();
if(quiz.choiceA.isSelected()){
System.out.println("wow");
}
else if(quiz.choiceB.isSelected()){
System.out.println("not wow");
}
else if(quiz.choiceD.isSelected()){
System.out.println("why doesn't this work?");
}
}
}
}
我只是希望每个字符串在被选中之后打印出来并按下JButton
,但是除非我在运行代码之前将其中一个设置为true,否则它们都不会工作,如果我这样做它就没有&#39 ;无论我检查了哪个单选按钮,当我点击JButton
来执行我最初设置为true的if语句时
答案 0 :(得分:4)
问题是您在Quiz
方法中创建actionPerformed
的新实例...
public void checkButtonActionPerformed(ActionEvent event){
Quiz quiz = new Quiz();
这意味着您所比较的内容并不是屏幕上的实际内容。
如果Handler
是内部类,则可以直接引用变量...
if(choiceA.isSelected()){...}
否则你应该将Quiz
的引用传递给Handler
以供它使用,但我会建议你这样做会变得更复杂,实际上需要某种可能的getter方法告诉我们选择了什么