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,否则它们都不起作用,如果我这样做了,我检查了哪个单选按钮都没有关系,当我点击JButton
to 时,我最初设置为 true 的 if 语句