java在不使用按钮事件的情况下初始化javafx场景
我在javafx项目中创建了一个名为quick\u scene的新场景和quick\u scene\u控制器。此场景模拟问答游戏。场景的对象是问题标签和回答文本字段或回答按钮。问题总数为7个,在系统引导到下一个场景之后
当我进入系统时,我希望在初始化函数中对sql数据库执行查询,并使用问题和答案获取当前问题和答案。当系统打开问答游戏场景时(以及每次按下回答按钮时),此过程需要发生一次。我试图在**@FXML public void initialize()**
中添加查询的功能,但是没有成功
当我尝试在按钮事件中添加功能时,查询起作用,并且我能够使用db中的信息更改场景的标签和按钮。我发现的一个问题是,当我执行查询时,我正在创建一个对我的主类的引用,该类包含测验场景的加载程序。如果没有事件,我不会检索当前对象,而是检索空对象。不使用按钮我怎么能这样做?为什么我的对象是空的
代码可以在这里找到:code
public class quizSceneController{
private Flow flow;
public void setMain(Flow flow){ this.flow = flow;}
@FXML Button answerbutton;
@FXML Text timeField, scoreField;
@FXML public Label question, showQuestionCounter, answer, questionId, questionType, questionSpeed;
NextQuestion nextQuestion;
public String temp, temp2;
public GridPane takingTestPane = new GridPane();
public void chooseNextQuestion(Flow flow){
try {
this.flow.nextQ = false;
this.flow.startTime = System.currentTimeMillis();
//Choosing the next question
String sql = "select * from Questions where Subject = ? and Level = ? and questionId = ?";
PreparedStatement pst =
this.flow.connectionQuestions.prepareStatement(sql);
pst.setString(1, this.flow.textSubjectQTest);
pst.setString(2, this.flow.user_course_level);
pst.setString(3, this.flow.list.get(counter));
ResultSet rs = pst.executeQuery();
if (rs.next()) {
temp = rs.getString("Question");
temp2 = rs.getString("Answer");
pst.execute();
pst.close();
} else {
System.out.println("No data for this subject");
}
} catch (Exception a) {
System.out.println(a);
}
}
@FXML private void myButton(ActionEvent event){
chooseNextQuestion(this.flow);
this.question.setText(temp);
}
@FXML public void initialize(){
chooseNextQuestion(this.flow);
this.question.setText(temp);
}
}
最后,我从主类加载fxml的方式如下:
loader = new FXMLLoader();
loader.setLocation(Flow.class.getResource("/gui/quiz/quiz.fxml"));
quizPane = loader.load();
quizSceneController quiz = loader.getController();
编辑:如何使用ChooseExtQuestion的代码来代替使用按钮初始化整个场景
# 1 楼答案
您可能正在执行以下操作来加载fxml文件:
但是
initialize
方法在FXMLLoader.load
期间执行,即在调用setMain
之前执行。当时flow
字段仍然包含null
要解决这个问题,可以在setter中执行以下代码:
或者,从fxml的根元素中删除
fx:controller
属性,并在加载fxml文件之前自己创建/初始化控制器:# 2 楼答案
控制器需要实现^{} 接口