gpt4 book ai didi

JavaFX - 在 Controller 类之间传递 int 值会产生不正确的结果

转载 作者:行者123 更新时间:2023-12-02 10:01:22 27 4
gpt4 key购买 nike

我正在制作一个小测验游戏,但是当我尝试将值从一个 Controller 传递到另一个 Controller 时,答案总是与我的预期相反。基本上,选择一个单选按钮,如果选择正确的单选按钮,则 returnValue()方法应该返回 1,否则返回 0。这告诉我用户是否选择了正确的答案。

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;
}
}

FinishScreen类(class)应该统计从所有 returnValue() 收集的分数。方法并显示分数,但无论我尝试什么,Question1无论单选按钮是否被选中,class 总是返回 0!我以前写过这样的代码并且运行良好,所以我很困惑。我还有 4 个这样的类(class)。

无论如何,这是FinishScreen类:

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());
}

}
}

我使用这篇文章中的信息作为如何将值从一个 Controller 传递到另一个 Controller 的引用: FXMLLoader getController returns NULL?

如果我尝试从 Question1 获取值的方式出现错误类是有意义的,但我读过的大多数其他帖子似乎也遵循这种设计模式。这是一个愚蠢的问题,但我无法弄清楚。

我的returnValue()rb2.isSelected() == true 时应该返回 1但事实并非如此。我尝试制作 score成员变量 static 也是如此,但这没有帮助。这里可能出现什么问题?

最佳答案

即使您使用static 字段来存储结果,当您调用returnValue 方法时,也会从场景中的控件中检索这些结果。

按照 calculateScore 方法中的方式第二次加载 fxml 会创建场景的新版本。在这个新版本的场景中,无论用户在其他版本的场景中完成什么输入,控件都处于初始状态。

我建议稍微重新设计应用程序:

  • 将问题的逻辑与“导航”问题的逻辑分开。
  • 保留 Controller 的引用信息以供以后评估。
  • 通过使用 Controller 实现界面,您可以让您的生活变得更轻松。

示例

private int questionIndex = -1;

@Override
public void start(Stage primaryStage) throws Exception {
StackPane questionContainer = new StackPane();
questionContainer.setAlignment(Pos.TOP_LEFT);
questionContainer.setPrefSize(300, 300);

// create question list repeating our only question
List<URL> questions = new ArrayList<>();
URL url = getClass().getResource("/my/package/question1.fxml");
for (int i = 0; i < 5; i++) {
questions.add(url);
}

List<QuestionController> questionControllers = new ArrayList<>(questions.size());

Button next = new Button("next");
EventHandler<ActionEvent> handler = evt -> {
if (questionIndex + 1 < questions.size()) {
questionIndex++;

// load next question & store controller for later evaluation
FXMLLoader loader = new FXMLLoader(questions.get(questionIndex));
try {
questionContainer.getChildren().setAll(loader.<Node>load());
questionControllers.add(loader.getController());
} catch (IOException e) {
throw new RuntimeException(e);
}
} else {
// display results
Alert alert = new Alert(AlertType.INFORMATION);
alert.setContentText("You've answered "
+ questionControllers.stream().mapToInt(QuestionController::getScore).sum()
+ " / " + questionControllers.size()
+ " questions correctly.");
alert.showAndWait();
primaryStage.close();
}
};
next.setOnAction(handler);

// activate first question
handler.handle(null);

primaryStage.setScene(new Scene(new VBox(questionContainer, next)));
primaryStage.show();
}
public interface QuestionController {
int getScore();
}
public class Question1Controller implements QuestionController {

private static final Random random = new Random();

private int correctAnswer;

@FXML
private List<RadioButton> buttons;

@FXML
private void initialize() {

// randomly assign correct answer
correctAnswer = random.nextInt(buttons.size());

for (RadioButton btn : buttons) {
btn.setText("incorrect");
}

buttons.get(correctAnswer).setText("correct");
}

@Override
public int getScore() {
return buttons.get(correctAnswer).isSelected() ? 1 : 0;
}
}
<?xml version="1.0" encoding="UTF-8"?>

<?import java.util.ArrayList?>
<?import javafx.scene.layout.VBox?>
<?import javafx.scene.control.RadioButton?>

<VBox xmlns:fx="http://javafx.com/fxml/1" fx:controller="my.package.Question1Controller">
<children>
<RadioButton fx:id="b1" />
<RadioButton fx:id="b2" />
<RadioButton fx:id="b3" />
<fx:define>
<ArrayList fx:id="buttons">
<fx:reference source="b1"/>
<fx:reference source="b2"/>
<fx:reference source="b3"/>
</ArrayList>
</fx:define>
</children>
</VBox>

关于JavaFX - 在 Controller 类之间传递 int 值会产生不正确的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55604682/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com