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に設定しない限り、どれも機能しません。そうすると、チェックしたラジオボタンは関係ありません。 toを押すJButtonと、最初にtrueに設定したifステートメントが実行されます

4

1 に答える 1

4

Quiz問題は、メソッドでの新しいインスタンスを作成していることactionPerformedです...

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

これは、比較しているものは実際に画面に表示されているものではないことを意味します。

が内部クラスの場合Handler、変数を直接参照できます...

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

Quizそれ以外の場合は、参照をに渡しHandlerて使用する必要がありますが、これはより複雑になることをお勧めします。実際には、何が選択されているかを伝えることができる何らかの種類のゲッター メソッドが必要です。

于 2013-07-25T00:52:11.910 に答える