How can I make constant variables in Javafx for XM

2020-02-28 23:32发布

问题:

StackPane layoutY="70.0" prefHeight="479.0". I want to make the values (70.0) and (479.0) static in a Java file so I can use them for other files.

Is this possible?

回答1:

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.



回答2:

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>