1

In my JavaFX programs thus far, I've used final variables to manage size such as:

final int SCENE_WIDTH = 500, SCENE_HEIGHT = 600,
ROOT_WIDTH = (int)(SCENE_WIDTH * 0.8), ROOT_HEIGHT = (int)(SCENE_HEIGHT * 0.8);

But people have told me that it's best to have GUI related sizing, colors, effects, etc to all be in the CSS file.

But in my CSS file, I don't think it's possible to create variables and have those update based on other variables. How would I accomplish the above with CSS? Which method makes the most sense?

1 Answer 1

2

Calculations like this are currently experimental technology for CSS 3 (see https://developer.mozilla.org/en/docs/Web/CSS/calc). JavaFX CSS is based on CSS 2.1.

Any multiplication of the size is only possible using the scale properties and this will behave a bit different to setting the prefered size to the result of a calculation.

@Override
public void start(Stage primaryStage) {
    Button btn = new Button("Say 'Hello World'");
    btn.setOnAction((ActionEvent event) -> {
        System.out.println("Hello World!");
    });

    StackPane root = new StackPane();
    root.setId("root");
    root.getChildren().add(btn);

    Scene scene = new Scene(root);
    scene.getStylesheets().add(getClass().getResource("style.css").toExternalForm());

    primaryStage.setScene(scene);
    primaryStage.show();
}
* {
    -fx-scene-width: 500;
    -fx-scene-height: 600;
}

#root {
    -fx-pref-width: -fx-scene-width;
    -fx-pref-height: -fx-scene-height;
}

.button {
    -fx-pref-width: -fx-scene-width;
    -fx-pref-height: -fx-scene-height;
    -fx-scale-x: 0.8;
    -fx-scale-y: 0.8;
}

Note that an attempt to set the size of the root to a different size than the scene size seems to be a bit non-sensical, since the Scene will set the root's size to it's own size regardless of any constraints specified on the root Node.


CSS is a good way of styling a scene in JavaFX, but it has some limitations. However you can use CSS and set/bind some values from code.

Sign up to request clarification or add additional context in comments.

2 Comments

"CSS is a good way of styling a scene in JavaFX, but it has some limitations. However you can use CSS and set/bind some values from code." Can you elaborate on this? Thank you.
@Hatefiend On what part in particular? The possibility to assign some properties from code and some from CSS? The limitations, e.g. that it's impossible to assign static properties or properties like Rectangle.width or calculate any values for most types and that some selectors, like sibling/child number selectors are not implemented in JavaFX?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.