如何在 Javafx 中为 XML 文件创建常量变量
How can I make constant variables in Javafx for XML files
StackPane layoutY="70.0"
prefHeight="479.0"
。我想在 Java 文件中将值 (70.0)
和 (479.0)
设为静态,以便我可以将它们用于其他文件。
这可能吗?
如果你的常量定义在class:
public class SomeClass {
public static final double DEFAULT_HEIGHT = 479 ;
// ...
}
然后您可以按如下方式在 FXML 中访问它:
<StackPane>
<prefHeight>
<SomeClass fx:constant="DEFAULT_HEIGHT" />
</prefHeight>
</StackPane>
确保您在 fxml 文件中为您正在使用的 class 导入了适当的文件。
James_D 向您展示了使用自定义 class 的方法。在 fxml 中执行此操作的另一种方法是定义您自己的变量。但它们不能跨文件共享。
而不是这个
<StackPane layoutY="70.0" prefHeight="479.0">
你想要
<StackPane layoutY="$variable" prefHeight="$variable">
你可以这样做
<?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>
StackPane layoutY="70.0"
prefHeight="479.0"
。我想在 Java 文件中将值 (70.0)
和 (479.0)
设为静态,以便我可以将它们用于其他文件。
这可能吗?
如果你的常量定义在class:
public class SomeClass {
public static final double DEFAULT_HEIGHT = 479 ;
// ...
}
然后您可以按如下方式在 FXML 中访问它:
<StackPane>
<prefHeight>
<SomeClass fx:constant="DEFAULT_HEIGHT" />
</prefHeight>
</StackPane>
确保您在 fxml 文件中为您正在使用的 class 导入了适当的文件。
James_D 向您展示了使用自定义 class 的方法。在 fxml 中执行此操作的另一种方法是定义您自己的变量。但它们不能跨文件共享。
而不是这个
<StackPane layoutY="70.0" prefHeight="479.0">
你想要
<StackPane layoutY="$variable" prefHeight="$variable">
你可以这样做
<?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>