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

4

1 回答 1

4

问题是您正在方法中创建一个新Quiz实例actionPerformed...

public void checkButtonActionPerformed(ActionEvent event){
    Quiz quiz = new Quiz();

这意味着您要比较的不是屏幕上实际显示的。

如果Handler是内部类,则可以直接引用变量...

if(choiceA.isSelected()){...}

否则你应该传递对它的引用QuizHandler供它使用,但我建议这会变得更复杂,实际上需要某种可以告诉你选择了什么的getter方法

于 2013-07-25T00:52:11.910 回答