如何在加载场景后更改按钮的文本和文本的文本

How to change Button's Text and Text's Text in a scene after loading it

我想在加载 fxml 后更改 Text 的值 file.EnglishQuestions class 是我的控制器 Question.fxml file.Please 忽略我刚刚使用的 Button 的参数它加载我之前场景的舞台。

我正在使用这段代码,但没有任何反应我想在加载 fxml 文件后每分钟更改一次按钮的文本和文本的文本,但是每当我尝试更改文本时,它都会给我 error.Here 我试图更改问题文本的文本,但没有成功。

    package try1;

    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import javafx.fxml.FXML;
    import javafx.fxml.FXMLLoader;
    import javafx.scene.Parent;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.scene.text.Text;
    import javafx.stage.Stage;


    public class EnglishQuestions {
        @FXML
        Text questionText;
        @FXML
        Button option1;
        @FXML
        Button option2;
        @FXML
        Button option3;
        @FXML
        Button option4;


      public void englishQuestions1(Button btn) throws Exception{
    //String q;
    //String op1,op2,op3,op4,ans;

     //loading FXML
        Stage window; 
          window =(Stage) btn.getScene().getWindow();
        Parent root = FXMLLoader.load(getClass().getResource("Question.fxml"));
Scene scene = new Scene(root,900,600);
window.setScene(scene);
questionText.setText("What is your name? ");
window.show();
    }}

您需要更改与您加载的 FXML 关联的控制器中的文本,而不是您加载 FXML 的控制器中的文本:

public void englishQuestions1(Button btn) throws Exception{
    Stage window; 
    window =(Stage) btn.getScene().getWindow();
    FXMLLoader loader = new FXMLLoader(getClass().getResource("Question.fxml"));
    Parent root = loader.load();
    EnglishQuestions controller = (EnglishQuestions) loader.getController();
    Scene scene = new Scene(root,900,600);
    window.setScene(scene);
    controller.questionText.setText("What is your name? ");
    window.show();
}