View logic inside fxml (iterating in particular)

亡梦爱人 提交于 2019-12-04 16:12:38

You may want to read Introduction to FXML and about Scripting in FXML.

The <fx:script> tag allows a caller to import scripting code into or embed script within a FXML file. Any JVM scripting language can be used, including JavaScript, Groovy, and Clojure, among others. Script code is often used to define event handlers directly in markup or in an associated source file, since event handlers can often be written more concisely in more loosely-typed scripting languages than they can in a statically-typed language such as Java.

However, I strongly advise against it. You want to find compile time errors, not runtime errors.

A brief example about how a script could look like, a label is added dynamically:

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

<?language javascript?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>


<VBox fx:id="root" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8">
    <children>
        <Button text="Button" />
        <Label text="Label" />
    </children>
    <fx:define>
        <Label fx:id="addedLabel" text="Label" />
    </fx:define>
    <fx:script>
        addedLabel.setText('Added Label');
        root.getChildren().add( addedLabel);
        java.lang.System.out.println( "Children: " + root.getChildren().size());
    </fx:script>
</VBox>

I won't go any deeper into this or lists or whatever scripting you want to do, because seriously: don't do it this way! Sooner or later you'll run into problems.

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