How can a textfield from fxml file be updated by setText in java file?

空扰寡人 提交于 2019-12-08 16:49:28

You can't use a constructor on your controller class (FXMLController), since it will be initilized by the FXMLLoader.

And you are right, the first link has a wrong answer, since the textfield will be initialized (because of the @FXML annotation) in this process.

So for starters, you can add some text to the textfield inside initialize, as it will be loaded from the beginning by the loader, and top will be already instantiated.

public class FXMLController implements Initializable {

    @FXML private TextField top;

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        top.setText("This is my first Text");
    } 
}

Try this first, with your posted version of JavaFXApplication5, and check that works.

There are many ways to set the content on the field, but if you need to modify the text field from another class, just add a public method for that:

public class FXMLController implements Initializable {

    @FXML private TextField top;

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        top.setText("This is my new Text");
    } 

    public void setTopText(String text) {
        // set text from another class
        top.setText(text);
    } 

}

As an example, you could get an instance of your controller in your main class, and use it to pass the content to the text field, after the stage is shown. This will override the previous content.

@Override
public void start(Stage stage) throws IOException {
    FXMLLoader loader = new FXMLLoader(getClass().getResource("FXML.fxml"));
    Parent root = loader.load();
    FXMLController controller = (FXMLController)loader.getController();

    Scene scene = new Scene(root);

    stage.setTitle("Java code");
    stage.setScene(scene);
    stage.show();

    controller.setTopText("New Text");
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!