我在javafx项目中创建了一个名为 quiz_scene 的新场景和 quiz_scene_controller 。这个场景模拟问答游戏。场景的对象是question_label和 answer_text_field 或 answer_buttons 。总共问题的数量是7,并且在系统进入下一个场景之后。
我想进入系统时,在初始化函数中对sql数据库执行查询,并提出问题和答案来获取当前的问题和答案。当系统打开quiz_scene时(以及每次按下应答按钮时),都需要执行此过程一次。我试图在**@FXML public void initialize()**
中添加查询的功能,但是它不起作用。
当我尝试在按钮事件中添加功能时,查询工作正常,我可以使用db中的信息更改场景的标签和按钮。我发现的一个问题是,当我执行查询时,我正在创建对包含quiz_scene的加载器的主类的引用。没有事件我没有检索当前对象,我正在检索一个空对象。如何在不使用按钮的情况下这样做?为什么我的对象是null?
可以在此处找到代码: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();
编辑:如何使用chooseNextQuestion的代码而不是使用按钮初始化整个场景?
答案 0 :(得分:6)
你可能正在做这样的事情来加载fxml文件:
FXMLLoader loader = new FXMLLoader(getClass().getResource("myFXML.fxml"));
Parent p = loader.load();
quizSceneController controller = loader.getController();
controller.setMain(this);
但initialize
方法在FXMLLoader.load
期间执行,即在调用setMain
之前执行。当时flow
字段仍包含null
。
要解决此问题,您可以在setter中执行代码:
public void setMain(Flow flow){
this.flow = flow;
chooseNextQuestion(this.flow);
this.question.setText(temp);
}
或者从fxml的根元素中删除fx:controller
属性,并在加载fxml文件之前自己创建/初始化控制器:
FXMLLoader loader = new FXMLLoader(getClass().getResource("myFXML.fxml"));
quizSceneController controller = new quizSceneController();
controller.setMain(this);
loader.setController(controller);
Parent p = loader.load();
答案 1 :(得分:2)
Your controller needs to implement the Initializable
interface
import javafx.fxml.Initializable;
public final class QuizSceneController implements Initializable {
@Override
public void initialize(URL location, ResourceBundle resources) {
// do stuff
}
}