How can I make constant variables in Javafx for XML files

我们两清 提交于 2019-11-30 14:15:36

If your constant is defined in a class:

public class SomeClass {

    public static final double DEFAULT_HEIGHT = 479 ;

    // ...
}

then you can access it in FXML as follows:

<StackPane>
    <prefHeight>
        <SomeClass fx:constant="DEFAULT_HEIGHT" />
    </prefHeight>
</StackPane>

Make sure you have the appropriate import in the fxml file for the class you are using.

James_D showed you the way of doing it with a custom class. Another way of doing it in fxml is to define your own variables. But they are not shareable across files.

Instead of this

<StackPane layoutY="70.0" prefHeight="479.0">

You want to have

<StackPane layoutY="$variable" prefHeight="$variable">

You be able to do it like this

<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<AnchorPane xmlns:fx="http://javafx.com/fxml/1" id="AnchorPane" prefHeight="200" prefWidth="320"  fx:controller="javafxapplication22.FXMLDocumentController">
  <fx:define>
    <Double fx:id="layoutY"  fx:value="70.0"/>
    <Double fx:id="prefHeight" fx:value="479.0"/>
  </fx:define>
  <children>
    <StackPane layoutY="$layoutY" prefHeight="$prefHeight"/>
    <Pane layoutY="$layoutY" prefHeight="$prefHeight"/>  
  </children>
</AnchorPane>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!