小编典典

将数据传递到控制器JAVAFX

java

我的图像是我试图将数据(变量)从一个阶段传递到另一阶段,但是当我尝试在第二阶段访问它们时,它们为空。mainWindow的代码。前往window1

 public class PrincipalController {
 private Stage primaryStage;
 public void initStage( Stage stage){ primaryStage = stage;}



@FXML
 private void goWindow1(ActionEvent event) {
    try {
         FXMLLoader miCargador = new
                 FXMLLoader(getClass().getResource("/vista/Window1.fxml"));
         Parent root = (Parent) miCargador.load();

                     // Access to window driver 1


 Window1Controller window1 = miCargador.
                  <window1Controlador>getController();
      windnow1.initStage(primaryStage);
      Scene scene = new Scene(root);
      primaryStage.setScene(scene);
      primaryStage.show();
     } catch (IOException e) {e.printStackTrace();}
    }
}

// window1类:

 public class Window1Controlador {
    private Stage primaryStage;
    private Scene escenaAnterior;
    private String tituloAnterior;
    public void initStage(Stage stage){
         primaryStage = stage;
         escenaAnterior = stage.getScene();
         tituloAnterior = stage.getTitle();
         primaryStage.setTitle("Window 1");
     }

如果我想访问以前收到的标题,则为null

/**
     * Initializes the controller class.
     * @param url
     * @param rb
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
       System.out.println(""+ this.tituloAnterior);}

初始化显示应该为“ Window1”时显示为null}


阅读 309

收藏
2020-11-30

共1个答案

小编典典

initialize()加载FXML文件的过程中,将调用该方法-换句话说,在调用时将调用该方法miCargador.load()

显然,这是 调用 之前
发生的window1.initStage(...),因此在initialize()被调用时tituloAnterior仍为null。

简单的解决方案是不访问tituloAnteriorinitialize()方法,但是做任何你需要在用它做initStage()的方法。例如

public void initStage(Stage stage){
     primaryStage = stage;
     escenaAnterior = stage.getScene();
     tituloAnterior = stage.getTitle();
     primaryStage.setTitle("Window 1");
     someLabelFromFXML.setText(tituloAnterior);
 }

如果愿意,可以在Java代码中为FXML加载程序设置控制器:

@FXML
private void goWindow1(ActionEvent event) {
    try {
         FXMLLoader miCargador = new
                 FXMLLoader(getClass().getResource("/vista/Window1.fxml"));

         Window1Controller window1 = new Window1Controller();
         window1.initStage(primaryStage);
         miCargador.setController(window1);

         Parent root = (Parent) miCargador.load();

                     // Access to window driver 1



      Scene scene = new Scene(root);
      primaryStage.setScene(scene);
      primaryStage.show();
     } catch (IOException e) {e.printStackTrace();}
    }
}

然后fx:controller从您的FXML文件中删除该属性。这样,方法在initStage()方法之前被调用load(),并且tituloAnteriorinitialize()被调用时不会为null

2020-11-30