8

I am searching for an EventListener or method that will run when I load an FXML file.

Does JavaFX have something similar to Javascript onLoad?

I simply want to run a method that will clear any data from the TextFields.

jewelsea
  • 150,031
  • 14
  • 366
  • 406
Lawyer_Coder
  • 203
  • 1
  • 3
  • 14

1 Answers1

17

Invoking code when an FXML is loaded

In your controller class, define a method:

@FXML
protected void initialize(URL location, Resources resources) 

This method will be invoked automatically by the FXMLLoader when the FXML file is loaded.

There is a sample in the Introduction to FXML (I've just replicated it here, slightly modified).

FXML

<VBox fx:controller="com.foo.MyController"
    xmlns:fx="http://javafx.com/fxml">
    <children>
        <Button fx:id="button" text="Click Me!"/>
    </children>
</VBox>

Java

package com.foo;

public class MyController implements Initializable {
    @FXML private Button button;

    @FXML
    protected void initialize(URL location, Resources resources) {
        button.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                System.out.println("You clicked me!");
            }
        });
    }
}

initialize() method without location and url

To simplify things, if your initialize method doesn't need access to the location used to resolve relative paths for the root object, or the resource bundle used to localize the root object, you can skip implementing Initializable and just define a public no-parameter initialize method, and the FXML loader will invoke that:

public void initialize() 

For further info see:

An observation based on your question

You may have a slight misunderstanding of how FXML processing works because when you load an FXML file, usually a new set of nodes are created (exceptions can be when you set the controller into the FXMLLoader or use the FXMLLoader in conjuction with a dependency injection system, but neither of those is probably your case). What this means is that there is no need to "run a method that will clear any data from the TextFields" because the text fields are new nodes and won't have any data in them unless you you set the text in the FXML (which you would not need to do if you are just going to clear it).

jewelsea
  • 150,031
  • 14
  • 366
  • 406
  • Thank you! One last question, another situation is where I want to pass an id variable to the second fxml controller and want to populate the text fields with data retrieved from a MYSQL DB. Right now I simply have a Button I press to retrieve the data and populate the fields. Where would I place the method/function to run that so that it runs upon the creation of the fxml page? – Lawyer_Coder Feb 20 '14 at 02:48
  • See [Passing parameters in FXML](http://stackoverflow.com/questions/14187963/passing-parameters-javafx-fxml). – jewelsea Feb 20 '14 at 03:02