Java .setBackground()方法不适用于JRadioButton

Java .setBackground()方法不适用于JRadioButton,java,swing,jradiobutton,Java,Swing,Jradiobutton,我正在编写一个包含测验元素的程序,当用户得到错误答案时,就会给出反馈。问题JFrame由一个具有实际问题的JLabel和4个具有不同选项的jRadioButton(命名为rad1、rad2、rad3、rad4)组成。我想做的是,如果用户错误地获得了asnswer,则具有正确答案的单选按钮的背景颜色将变为绿色,而具有用户给出的答案的单选按钮的背景颜色将变为红色 下面是我用来找出哪个答案正确的FOR循环: private void btnSubmitActionPerformed(java.awt.

我正在编写一个包含测验元素的程序,当用户得到错误答案时,就会给出反馈。问题JFrame由一个具有实际问题的JLabel和4个具有不同选项的jRadioButton(命名为rad1、rad2、rad3、rad4)组成。我想做的是,如果用户错误地获得了asnswer,则具有正确答案的单选按钮的背景颜色将变为绿色,而具有用户给出的答案的单选按钮的背景颜色将变为红色

下面是我用来找出哪个答案正确的FOR循环:

private void btnSubmitActionPerformed(java.awt.event.ActionEvent evt) {                                          
    System.out.println("Submit Clicked");
    //figures out what choice the user selected
    String correctAnswer = questions.get(current).getAnswer();
    int numChoice = -1;
    String choice = "";
    boolean answered = false;

    if (rad1.isSelected()) {
        numChoice = 0;
        answered = true;
        choice = rad1.getText();
    } else if (rad2.isSelected()) {
        numChoice = 1;
        answered = true;
        choice = rad2.getText();
    } else if (rad3.isSelected()) {
        numChoice = 2;
        answered = true;
        choice = rad3.getText();
    } else if (rad4.isSelected()) {
        numChoice = 3;
        answered = true;
        choice = rad4.getText();
    } else { //user didn't pick a choice
        JOptionPane.showMessageDialog(null, "You didn't answer the question, try again!");
    }

    if (choice.equals(correctAnswer)) {
        score++;
        System.out.println("score++");
    } else {
        //figures out which of the answers was correct
        rad1.setBackground(Color.RED);
        for (int i = 0; i < 4; i++) {
            if (questions.get(current).getChoices()[i].equals(correctAnswer)) {
                System.out.println(correctAnswer);
                System.out.println(i);
                //me trying to see if it will change if I put it outside the switch
                //confirmed that it will not.
                rad1.setBackground(Color.RED);
                switch (i) {
                    case 0:
                        rad1.setBackground(new Color(51, 204, 51));
                        break;
                    case 1:
                        rad2.setBackground(new Color(51, 204, 51));
                        break;
                    case 2:
                        rad3.setBackground(new Color(51, 204, 51));
                        break;
                    case 3:
                        rad4.setBackground(new Color(51, 204, 51));
                        break;
                }
                break;
            }

        }
        switch (numChoice) {
            case 0:
                rad1.setBackground(new Color(153, 0, 0));
                break;
            case 1:
                rad2.setBackground(new Color(153, 0, 0));
                break;
            case 2:
                rad3.setBackground(new Color(153, 0, 0));
                break;
            case 3:
                rad4.setBackground(new Color(153, 0, 0));
                break;
        }
    }
    //loads next question


    //loads the next question
    if (current < 10) {
        updateFrame();
    } else {
        //ends the quiz
    }
}                    
private void btnSubmitActionPerformed(java.awt.event.ActionEvent evt){
System.out.println(“单击提交”);
//找出用户选择的选项
String correctAnswer=questions.get(当前).getAnswer();
int numChoice=-1;
字符串选择=”;
布尔值=假;
if(rad1.isSelected()){
numChoice=0;
回答=正确;
choice=rad1.getText();
}else if(rad2.isSelected()){
numChoice=1;
回答=正确;
choice=rad2.getText();
}else if(rad3.isSelected()){
numChoice=2;
回答=正确;
choice=rad3.getText();
}else if(rad4.isSelected()){
numChoice=3;
回答=正确;
choice=rad4.getText();
}否则{//用户没有选择
showMessageDialog(null,“您没有回答问题,请重试!”);
}
if(选择等于(正确答案)){
分数++;
System.out.println(“score++”);
}否则{
//找出哪一个答案是正确的
rad1.立根背景(颜色:红色);
对于(int i=0;i<4;i++){
if(questions.get(current.getChoices()[i].equals(correctAnswer)){
系统输出打印项次(正确答案);
系统输出打印LN(i);
//我试着看看如果我把它放在开关外面它是否会改变
//证实不会。
rad1.立根背景(颜色:红色);
开关(一){
案例0:
rad1.挫折背景(新颜色(51、204、51));
打破
案例1:
rad2.背景(新颜色(51、204、51));
打破
案例2:
rad3.挫折背景(新颜色(51、204、51));
打破
案例3:
rad4.挫折背景(新颜色(51、204、51));
打破
}
打破
}
}
开关(numChoice){
案例0:
退化背景(新颜色(153,0,0));
打破
案例1:
退化背景(新颜色(153,0,0));
打破
案例2:
退化背景(新颜色(153,0,0));
打破
案例3:
退化背景(新颜色(153,0,0));
打破
}
}
//下一个问题
//加载下一个问题
如果(电流<10){
updatename();
}否则{
//测验结束
}
}                    
我使用.setBackground()方法已经有一段时间了,如果我将print语句放在case块中,它们就会执行,但不会着色。有没有什么愚蠢的东西我错过了

谢谢


编辑:添加了更多代码以查看FOR循环在btnSubmitActionPerformed()方法中。当用户单击按钮时,将判断其答案,并更改单选按钮的颜色

我马上想到两件事:

  • 从哪里调用您发布的代码?在Swing worker线程之外进行UI更改有点未定义。有时会发生正确的事情,但有时不会
  • 我从未尝试过设置单选按钮的颜色,但它们似乎没有背景

  • 试着设置一些其他属性,比如大小,看看是否有结果。如果是这样,那么问题是单选按钮没有背景,你必须想出另一种设计。如果什么也没有发生,那么这可能是第一个问题。

    您的代码看起来过于复杂,不必要。我自己,我会尝试“OOP-ify”的东西,以减少圈复杂度和

    • 一堂非贵问题课
    • 带有用于提问文本的字符串字段
    • 使用字符串字段作为correctAnswer
    • 对于不正确的回答,使用
      列表
    • 我会给它一个方法,比如说
      public List getShuffledAnswers()
      ,返回一个字符串列表,其中包含所有答案,包括正确答案和错误答案,并在它们自己的列表中混洗
    • 一种布尔方法,用于
      测试回答(字符串测试)
      ,测试返回true等于正确答案
    然后我会创建一个名为QuestionPanel的JPanel

    • 这有一个问题
    • 显示单个问题对象的信息,包括JLabel中的问题文本和JRadioButtons中的所有混合答案
    • 它将具有获取所选JRadioButton和获取问题的方法
    • 以及一种设置方法,通过调用`setOpaque(false),在需要时使JRadioButtons背景不不透明
    • 以及允许调用代码使用正确答案颜色或错误答案颜色设置select JRadioButtons的背景的方法
    例如:

    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.List;
    
    import javax.swing.AbstractAction;
    import javax.swing.BorderFactory;
    import javax.swing.ButtonGroup;
    import javax.swing.ButtonModel;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JRadioButton;
    import javax.swing.SwingUtilities;
    
    @SuppressWarnings("serial")
    public class TestQuestions extends JPanel {
        private static final Question TEST_QUESTION = new Question("Select the Correct Answer", "This answer is correct", 
                "Incorrect Answer 1", "Incorrect Answer 2", "Incorrect Answer 3");
        private QuestionPanel questionPanel = new QuestionPanel();
    
        public TestQuestions() {
            questionPanel.setQuestion(TEST_QUESTION);
            JButton testAnswerBtn = new JButton(new AbstractAction("Test Answer") {
    
                @Override
                public void actionPerformed(ActionEvent e) {
                    boolean isCorrect = questionPanel.isCorrectAnswerSelected();
                    String message = "";
                    if (isCorrect) {
                        message = "Correct answer selected!";
                    } else {
                        message = "Incorrect answer selected!";                    
                    }
                    JOptionPane.showMessageDialog(TestQuestions.this, message);
                    questionPanel.displayCorrectWrongAnswers();
                }
            });
            JButton clearAllBtn = new JButton(new AbstractAction("Clear All") {
    
                @Override
                public void actionPerformed(ActionEvent e) {
                    questionPanel.clearAll();
                    questionPanel.clearSelection();
                }
            });
    
            JPanel btnPanel = new JPanel(new GridLayout(1, 0, 5, 5));
            btnPanel.add(testAnswerBtn);
            btnPanel.add(clearAllBtn);
    
            setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
            setLayout(new BorderLayout(5, 5));
            add(questionPanel, BorderLayout.CENTER);
            add(btnPanel, BorderLayout.PAGE_END);
        }
    
        private static void createAndShowGui() {
            JFrame frame = new JFrame("TestQuestions");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.getContentPane().add(new TestQuestions());
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGui();
                }
            });
        }
    }
    
    @SuppressWarnings("serial")
    class QuestionPanel extends JPanel {
        private static final Color CORRECT_ANSWER_SELECTED_COLOR = new Color(151, 255, 151);
        private static final Color CORRECT_ANSWER_NOT_SELECTED_COLOR = new Color(151,151, 255);
        private static final Color INCORRECT_ANSWER_SELECTED_COLOR = new Color(255, 151, 151);
        private Question question;
        private JLabel questionTextLabel = new JLabel();
        private List<JRadioButton> answerButtonList = new ArrayList<>();
        private JPanel answerPanel = new JPanel(new GridLayout(0, 1));
        private ButtonGroup buttonGroup = new ButtonGroup();
    
        public QuestionPanel() {
            setLayout(new BorderLayout());
            add(questionTextLabel, BorderLayout.PAGE_START);
            add(answerPanel, BorderLayout.CENTER);
        }
    
        public void setQuestion(Question question) {
            this.question = question;
            questionTextLabel.setText(question.getQuestionText());
    
            answerPanel.removeAll();
            answerButtonList.clear();
            buttonGroup = new ButtonGroup();
    
            for (String answer : question.getShuffledAnswers()) {
                JRadioButton rBtn = new JRadioButton(answer);
                rBtn.setActionCommand(answer);
                answerButtonList.add(rBtn);
                buttonGroup.add(rBtn);
                answerPanel.add(rBtn);
            }
        }
    
        public boolean isCorrectAnswerSelected() {
            ButtonModel model = buttonGroup.getSelection();
            if (model == null) {
                return false; // nothing selected
            } else {
                return question.checkAnswer(model.getActionCommand());
            }
        }
    
        public void clearAll() {
            for (JRadioButton jRadioButton : answerButtonList) {
                jRadioButton.setOpaque(false);
                jRadioButton.setBackground(null);
            }
        }
    
        public void clearSelection() {
            buttonGroup.clearSelection();
        }
    
        public void displayCorrectWrongAnswers() {
            clearAll();
            for (JRadioButton jRadioButton : answerButtonList) {
                if (jRadioButton.isSelected()) {
                    jRadioButton.setOpaque(true);
                    if (question.checkAnswer(jRadioButton.getActionCommand())) {
                        jRadioButton.setBackground(CORRECT_ANSWER_SELECTED_COLOR);
                    } else {
                        jRadioButton.setBackground(CORRECT_ANSWER_NOT_SELECTED_COLOR);
                    }
                } else if (question.checkAnswer(jRadioButton.getActionCommand())) {
                    jRadioButton.setOpaque(true);
                    jRadioButton.setBackground(INCORRECT_ANSWER_SELECTED_COLOR);
                }
            }
        }
    
    }
    
    class Question {
        private String questionText;
        private String correctAnswer;
        private List<String> incorrectAnswerList = new ArrayList<>();
        public Question(String questionText, String correctAnswer, String... incorrectAnswers) {
            this.questionText = questionText;
            this.correctAnswer = correctAnswer;
            for (String incorrectAnswer : incorrectAnswers) {
                incorrectAnswerList.add(incorrectAnswer);
            }
        }
    
        public String getQuestionText() {
            return questionText;
        }
    
        public String getCorrectAnswer() {
            return correctAnswer;
        }
    
        public List<String> getShuffledAnswers() {
            List<String> answers = new ArrayList<>(incorrectAnswerList);
            answers.add(correctAnswer);
            Collections.shuffle(answers);
            return answers;
        }
    
        public boolean checkAnswer(String test) {
            return correctAnswer.equalsIgnoreCase(test);
        }
    
    }
    
    导入java.awt.BorderLayout;
    导入java.awt.Color;
    导入java.awt.GridLayout;
    导入java.awt.event.ActionEvent;
    导入java.util.ArrayList;
    导入java.util.Collections;
    导入java.util.List;
    导入javax.swing.AbstractAction;
    进口ja