I have a little quiz game I'm making, however when I try to pass a value from one of my controllers to another, the answer is always the opposite of what I expect. Basically, a radio button is selected, and if the correct one is selected, the returnValue()
method should return a 1, else 0. This tells me if the user selected the proper answer or not.
Code for controller 1:
public class Question1
{
@FXML
private Label question1Lbl;
@FXML
private RadioButton rb1;
@FXML
private RadioButton rb2;
@FXML
private RadioButton rb3;
private static int score;
public void nextQuestion(ActionEvent actionEvent)
{
try
{
FXMLLoader loader = new FXMLLoader(getClass().getResource("../gui/Question2.fxml"));
Parent rootPane = loader.load();
Stage primaryStage = new Stage();
primaryStage.setScene(new Scene(rootPane));
primaryStage.setResizable(false);
primaryStage.setTitle("Frage 2");
primaryStage.show();
rb1.getScene().getWindow().hide();
}
catch (Exception e)
{
System.out.println("Error loading question 1" + e.toString());
e.printStackTrace();
}
}
//returns the points for this question. 1 for correct, 0 for incorrect
public int returnValue()
{
if (!rb2.isSelected())
{
score = 0;
return score;
}
score = 1;
return score;
}
}
The FinishScreen
class is supposed to tally up the points gathered from all the returnValue()
methods and display a score, but no matter what I try, the Question1
class always returns 0, whether the radio button was selected or not! I've written code like this before and it's worked fine, so I'm confused. I have 4 more classes like this, too.
Anyway, here is the FinishScreen
class:
public class FinishScreen implements Initializable
{
@FXML
private Label resultLbl;
private int totalScore;
public void calculateScore() throws Exception
{
FXMLLoader loader1 = new FXMLLoader(getClass().getResource("../gui/Question1.fxml"));
Parent root1 = loader1.load();
Question1 q1 = loader1.getController();
totalScore = q1.returnValue();
System.out.println(totalScore);
resultLbl.setText("Score: " + totalScore);
}
@Override
public void initialize(URL location, ResourceBundle resources)
{
try
{
calculateScore();
}
catch (Exception e)
{
System.out.println("Error in results " + e.toString());
}
}
}
I used info from this post as a reference for how to pass values from one controller to another: FXMLLoader getController returns NULL?
If there is an error in the way I am trying to get the value from my Question1
class that would make sense, but most other posts I've read seem to follow this design pattern as well. It is a silly problem to have, yet I cannot figure it out.
My returnValue()
should return a 1 when rb2.isSelected() == true
but that isn't the case. I tried making the score
member variable static as well and that hasn't helped. What could be the issue here?