问题
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)?
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/16621989/fxml-script-tag-and-initialize-method