nanakondor
nanakondor

Reputation: 745

set style for a bunch of labels in javafx

i would like to set font size for many labels and possibly without the use of external css file.

I tried using Group and setStyle, but it didn't work. (I know how to set style for a label, but not a class of labels)

Group label_group = new Group();
Label lb1 = new Label("1");
Label lb2 = new Label("2");
label_group.getChildren().addAll(lb1, lb2);
label_group.setStyle("-fx-font-size:20");
Label lb1 = new Label("1");
Label lb2 = new Label("2");
label_group.getChildren().addAll(lb1, lb2);
label_group.setStyle("-fx-font-size:20");

The font size of both labels dont change to 20. How do I define a property for 10 labels ? I'm not sure on how to use external CSS file also, if its the only way.

Upvotes: 1

Views: 3477

Answers (2)

Rene Ferguson
Rene Ferguson

Reputation: 39

If you're interesting in learning how to do it with CSS, you could have the following CSS file called "myStyle.css" in your project's resource directory

.label{
    -fx-font-size:20
} 

and then in your java code

Label lb1 = new Label("1");
Label lb2 = new Label("2"); 
scene.getStylesheets().add(yourClassName.class.getResource("myStyle.css").toExternalForm());

where scene is whatever scene you are putting your labels in (you can also use stage.getScene() if you need). All of your labels should then use that style so you won't have to manually set it every time, and you can add additional properties to your CSS file too. I learned how to use this recently and I find that it makes my code look a lot less messy.

Upvotes: 0

Zephyr
Zephyr

Reputation: 10253

If you want a number of Node objects to share the same style (without an external CSS stylesheet), just use a simple method that accepts an indefinite number of arguments (called "varargs" in Java, for "variable arguments") to apply them:

private void setStyle(Node... nodes) {
    for (Node node : nodes) {
        node.setStyle("-fx-font-size: 20");
    }
}

Then you can call the method, passing all of your labels at once:

setStyle(lb1, lb2, lb3);

Upvotes: 6

Related Questions