在 fxml 布局中使用常量
Using constants in fxml layout
在我的 FXML 项目中,我不想对布局中的所有常量进行硬编码。简单的东西,比如边距和填充。我宁愿把它们都放在一个地方。我该怎么做?
我可以创建一个带有常量的 class 并在我的 fxml 布局中访问它们吗?我知道 fx:define 但我必须在每个 fxml 文件中重复这一点。或者有没有办法在中央文件中 fx:define 并将其附加到我所有的 fxml 布局?或者也许有类似于我用于内部化的资源包的东西?
在可能的情况下,我建议使用 CSS 样式表。
虽然 css 中的所有属性都没有等效项。对于那些您可以在调用加载之前初始化 FXMLLoader.namespace
映射。 namespace
的条目可以像使用条目的键定义为 fx:id
:
一样使用
@Override
public void start(Stage primaryStage) throws IOException {
FXMLLoader loader = new FXMLLoader(getClass().getResource("test.fxml"));
// initialize namespace
Map<String, Object> namespace = loader.getNamespace();
namespace.put("a", 10d);
namespace.put("b", 20d);
Scene scene = new Scene(loader.load());
primaryStage.setScene(scene);
primaryStage.show();
}
test.fxml
<Pane prefHeight="400.0" prefWidth="600.0" xmlns:fx="http://javafx.com/fxml/1">
<children>
<Rectangle x="$a" y="10" width="20" height="20">
<fill>
<Color fx:constant="BLUE"/>
</fill>
</Rectangle>
<Rectangle x="$b" y="30" width="20" height="20">
<fill>
<Color fx:constant="RED"/>
</fill>
</Rectangle>
</children>
</Pane>
在我的 FXML 项目中,我不想对布局中的所有常量进行硬编码。简单的东西,比如边距和填充。我宁愿把它们都放在一个地方。我该怎么做?
我可以创建一个带有常量的 class 并在我的 fxml 布局中访问它们吗?我知道 fx:define 但我必须在每个 fxml 文件中重复这一点。或者有没有办法在中央文件中 fx:define 并将其附加到我所有的 fxml 布局?或者也许有类似于我用于内部化的资源包的东西?
在可能的情况下,我建议使用 CSS 样式表。
虽然 css 中的所有属性都没有等效项。对于那些您可以在调用加载之前初始化 FXMLLoader.namespace
映射。 namespace
的条目可以像使用条目的键定义为 fx:id
:
@Override
public void start(Stage primaryStage) throws IOException {
FXMLLoader loader = new FXMLLoader(getClass().getResource("test.fxml"));
// initialize namespace
Map<String, Object> namespace = loader.getNamespace();
namespace.put("a", 10d);
namespace.put("b", 20d);
Scene scene = new Scene(loader.load());
primaryStage.setScene(scene);
primaryStage.show();
}
test.fxml
<Pane prefHeight="400.0" prefWidth="600.0" xmlns:fx="http://javafx.com/fxml/1">
<children>
<Rectangle x="$a" y="10" width="20" height="20">
<fill>
<Color fx:constant="BLUE"/>
</fill>
</Rectangle>
<Rectangle x="$b" y="30" width="20" height="20">
<fill>
<Color fx:constant="RED"/>
</fill>
</Rectangle>
</children>
</Pane>