2

I am testing and discovering JavaFX.

In JavaFX FXML documentation about controllers, it is said that if the controller has a public void initialize() method, it is called once the FXML graph is loaded.

Is it possible to do something similar, but from the FXML file in a script way? I tried something like that, but initialize() is not called at all.

<?xml version="1.0" encoding="UTF-8"?>

<?language javascript?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.AnchorPane?>

<AnchorPane xmlns:fx="http://javafx.com/fxml">

    <fx:script>
    importClass(java.lang.System);

    function initialize() {
        System.out.println('hello');
    }  
    </fx:script>

    <Button text="Button" />

</AnchorPane>

Do I miss something, or is just not possible to do that from the FXML file?

Is there a kind of workaround so the FXML file can embed some codes that will automatically execute after it is loaded (without using an external Java controller file)?

Vincent Hiribarren
  • 5,254
  • 2
  • 41
  • 65

2 Answers2

2

I think the scripts in the fxml will just be executed inline just like they are in HTML. So you don't place the script statements to be executed inside any function.

See this fxml+JavaScript metronome application for a sample.

jewelsea
  • 150,031
  • 14
  • 366
  • 406
1

The controller must also implement the javafx.fxml.Initializable interface. for the initialize method to be called. The code example of a controller shows this but the description is not very clear.

I'm not sure about the FXML scripting.

Andy Till
  • 3,371
  • 2
  • 18
  • 23
  • 1
    It seems it changed. According to the documentation http://docs.oracle.com/javafx/2/api/javafx/fxml/Initializable.html "This interface has been superseded by automatic injection of location and resources properties into the controller. FXMLLoader will now automatically call any suitably annotated no-arg initialize() method defined by the controller. It is recommended that the injection approach be used whenever possible." – Vincent Hiribarren May 18 '13 at 09:07
  • 1
    Ha, you learn something every day. The injection method (which has a different signature to the method in Initalizable) seems even less documented than the interface. Are resources a field that is annotated with @FXML. – Andy Till May 18 '13 at 09:12