Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaFX 2.2 onLoad Method equivalent

Tags:

javafx-2

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.

like image 586
Lawyer_Coder Avatar asked Feb 20 '14 01:02

Lawyer_Coder


1 Answers

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:

  • JavaFX FXML Controller initialize method not invoked

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).

like image 71
jewelsea Avatar answered Oct 21 '22 03:10

jewelsea