Hot to update dynamically font size

2019-07-18 09:27发布

问题:

I have this css file which sets the default font size and type in JavaFX application:

.root {
  -fx-font: 13px Tahoma;
}

scene.getStylesheets().add(getClass().getResource("/styles/Styles.css").toExternalForm());

I want to update the size and the font type from the Java code dynamically of the root component (all components). How I can do this?

Note: This code updates the Font type and size of all components into the JavaFX application.

回答1:

Please consider taking a look at the official JavaFX documentation. There you find the code example which answers your question:

Text t = new Text("That's the text");
t.setFont(Font.font ("Verdana", 20));

UPDATE

In your application controller get an instance of your root pane, e.g. AnchorPane and use the setId("") function to set new style for the whole pane (my actionChange is connected with a button on the pane, which triggers the event/change):

public class AppController implements Initializable {
    @FXML
    private AnchorPane mainPane;

    @Override
    public void initialize(URL arg0, ResourceBundle arg1) {
        // TODO Auto-generated method stub
    }

    @FXML
    public void actionChange() {
        mainPane.setId("fancytext");
    }
}

When pressing the button, the style for the pane is changed. I just used the font-size as an example. Before, you need to specify the new style in your CSS file:

.root {
    -fx-font: 12px Tahoma;
}

#fancytext {
    -fx-font: 20px Tahoma;
}

That's before:

That's after the button was pressed: