I'm writing a program that has a quiz element, and when the user gets an answer wrong, feedback is given. The question JFrame is made of a JLabel that has the actual question, and 4 JRadioButtons that have the different options (named rad1, rad2, rad3, rad4). What I'm trying to do is if the user gets an asnswer wrong, the radio button with the correct answer's background colour turns green and the radio button with the answer that the user gave's background turns red.
Here's the FOR loop that I'm using to figure out which of the answers is correct:
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
}
}
I've been playing around with the .setBackground() method for a while, and if I put print statements in the case blocks, they execute, but the colouring doesn't happen. Is there something dumb that I'm missing?
Thanks
EDIT: Added more code to see that the FOR loop is within the btnSubmitActionPerformed() method. When the user clicks the button, their answer is to be judged and the colour of the radio button is to be changed.