在fxml布局中使用常量 [英] Using constants in fxml layout

查看:214
本文介绍了在fxml布局中使用常量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的FXML项目中,我不想硬编码布局中的所有常量。简单的事情,如边距和填充。我宁愿把它们放在一个地方。我该怎么做?



我可以用常量创建一个类并在我的fxml布局中访问它们吗?我知道fx:define但我必须在每个fxml文件中重复这个。或者有没有办法fx:在中央文件中定义并将其附加到我的所有fxml布局?或者也许有类似于我用于内化的资源包?

解决方案

我建议使用CSS样式表。



但是css中的所有属性都没有等价物。对于那些你可以在调用load之前初始化 FXMLLoader.namespace 映射。可以使用命名空间的条目,就好像它们是使用条目的键定义为 fx:id

  @Override 
public void start(Stage primaryStage)抛出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);

场景场景=新场景(loader.load());

primaryStage.setScene(scene);
primaryStage.show();
}



test.fxml



< pre class =lang-xml prettyprint-override> < Pane prefHeight =400.0prefWidth =600.0xmlns:fx =http://javafx.com/fxml/1>
< children>
< Rectangle x =$ ay =10width =20height =20>
< fill>
< Color fx:constant =BLUE/>
< / fill>
< / Rectangle>
< Rectangle x =$ by =30width =20height =20>
< fill>
< Color fx:constant =RED/>
< / fill>
< / Rectangle>
< / children>
< / Pane>


In my FXML Project I don't want to hardcode all the constants in my layout. Simple things like margins and paddings. I'd prefer to keep them all in one place. How would I do that?

Can I create a class with constants and access them in my fxml layouts? I know about fx:define but I would have to repeat this in every fxml file. Or is there a way to fx:define in a central file and append this to all my fxml layouts? Or maybe there is something similar to resource bundles which I use for internalization?

解决方案

Where it's possible I recommend using a CSS stylesheet.

There is no equivalent for all properties in css though. For those you could initialize the FXMLLoader.namespace map before calling load. The entries of the namespace can be used as if they were defined using the key of the entry as 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布局中使用常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆