Search code examples
javajavafxconstantsfxml

Using constants in fxml layout


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?


Solution

  • 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>