我如何在 Main 的 FXML 文件中引用某些内容?

How would I reference something in From a FXML file, in Main?

大家好,我正在努力学习 JavaFX。

无论如何我都可以更改 main.java 文件中的这些节点或元素之一。 我将如何更改 main.java 文件中的 lowTextField 文本?

我尝试使用
lowTextField.setText("Still learning");在 start 方法中,这会引发各种错误。空指针等。这是因为我不知道如何从 main java 中的 fxml 引用该文本字段。 我该怎么做?

这是主要内容:

public class Main extends Application {

  @Override
     public void start(Stage primaryStage) throws Exception{
          Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
    primaryStage.setTitle("Hello World");
    primaryStage.setScene(new Scene(root, 300, 275));
    primaryStage.show();

        lowTextField.setText("This is The Console"); //<<this des not work


   }


public static void main(String[] args) {
    launch(args);
   }
 }

这是我的控制器文件。它现在什么都不做,但我知道控制器用于操作、输入等。

          public class Controller{

@FXML Button toolBarBtn1;
@FXML Button toolBarBtn2;
@FXML TextField lowTextField;
@FXML public BorderPane Root;

   }

我知道我正在做的事情真的很简单,但我只是想了解一下。

非常感谢任何帮助。

如果您在控制器中定义一个 initialize() 方法,它将在注入 @FXML-注释字段后调用,因此您可以在那里访问它们:

public class Controller{

    @FXML Button toolBarBtn1;
    @FXML Button toolBarBtn2;
    @FXML TextField lowTextField;
    @FXML BorderPane Root;

    public void initialize() {
        lowTextField.setText("This is The Console"); 
    }

}

理想情况下,您不希望直接更改不同 class 中的字段。相反,在您的控制器 class 中,创建 setter 和 getter 来操作字段。

这是您可以在 Controller.java 中放置的示例:

public void setLowTextField (String text) {
  this.lowTextField.setText(text);  // Calls the setText() method of the local TextField
}

然后在您的 Main.java 文件中,在创建控制器后调用该方法。

FXMLLoader loader = new FXMLLoader(getClass().getResource("sample.fxml"));

// You first need to create a reference to your controller
Controller controller = new Controller();
loader.setController(controller);

Parent root = loader.load()

// Now call the setter from the Controller.java file:
controller.setLowTextField("This is The Console");

primaryStage.setTitle("Hello World");
primaryStage.setScene(new Scene(root, 300, 275));
primaryStage.show();

这被认为是最佳实践,因为您可以在 Controller.java 中将您的 @FXML 变量声明为私有,但仍然可以从 Main class.

访问它们