Issue
I'm developing a piece of software which allows you to change the font that it uses for displaying text (when I say text I mean the text inside of Labels, TextArea's, Buttons, etc).
For example, in my program, I have 6 Labels, 4 Buttons and 3 TextArea's along with a Font object:
Font myFont = new Font(20);
Label l1 = new Label("text1");
Label l2 = new Label("text2");
Label l3 = new Label("text3");
Label l4 = new Label("text4");
Label l5 = new Label("text5");
Label l6 = new Label("text6");
Button b1 = new Button("button1");
Button b2 = new Button("button2");
Button b3 = new Button("button3");
Button b4 = new Button("button4");
TextArea t1 = new TextArea("text1");
TextArea t2 = new TextArea("text2");
TextArea t3 = new TextArea("text3");
How can I apply myFont to every single one of these object without having to write .setFont() for every single one of them?
Solution
The correct way to do this would be to apply a style sheet to the Scene where you specify the -fx-font. See https://docs.oracle.com/javase/8/javafx/api/javafx/scene/doc-files/cssref.html#typefont
Since the -fx-font attribute is inherited by many classes, you may be able to cover most text by specifying this for the root node. https://docs.oracle.com/javase/8/javafx/api/javafx/scene/doc-files/cssref.html#introinheritance
I find looking at the CSS for the built-in styles is helpful when adjusting styles with CSS: https://github.com/openjdk/jfx/blob/master/modules/javafx.controls/src/main/resources/com/sun/javafx/scene/control/skin/modena/modena.css
public class Main extends Application {
public static void main(final String[] args) {
launch(args);
}
@Override
public void start(final Stage primaryStage) throws Exception {
String myStyles = """
.root {
-fx-font: 24 monospace;
}
""";
File cssFile = File.createTempFile("demo", "css");
cssFile.deleteOnExit();
Files.writeString(cssFile.toPath(), myStyles, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
String cssURL = cssFile.toURI().toString();
VBox box = new VBox(4,
new Label("This is a label."),
new TextField("This is a text field."),
new Button("This is a button."));
box.setPadding(new Insets(4));
Scene scene = new Scene(box);
scene.getStylesheets().add(cssURL);
primaryStage.setScene(scene);
primaryStage.show();
}
}
Answered By - swpalmer