We can apply the styles from a css file easily, which are fixed values defined in css, to any element in JavaFx directly by calling getStyleSheets() or getStyleClass().However, think of a scenario where the colours and styles are to be applied dynamically based on the unknown number of choices made available to the user. In this scenario, creating a separate style (or style class) per colour (or style) is practically not possible. However, here is an approach to apply dynamic styles.
With that being said, if you have any other method, I request you to share it and help others to learn more.
Source Code:
public class CssDemo extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Hello World!");
final Button btn = new Button();
btn.setText("Say 'Hello World'");
btn.setOnAction(new EventHandler() {
@Override
public void handle(ActionEvent event) {
try {
String prefix = "background_";
String suffix = ".css";
// this temporary file remains after the jvm exits
File tempFile = File.createTempFile(prefix, suffix);
// to delete the files created in temp after the application closes
// deletion happens only if the application exits properly
tempFile.deleteOnExit();
String cssContent = ".intro { -fx-background-color: rgb("
+ 67 + "," + 98 + "," + 288 + ")}";
BufferedWriter bw = new BufferedWriter(new FileWriter(tempFile));
bw.write(cssContent);
bw.close();
String filename = tempFile.getPath();
btn.getStylesheets().add("file:///" + filename);
btn.getStyleClass().add("intro");
} catch (Exception e) {
e.printStackTrace();
}
}
});
StackPane root = new StackPane();
root.getChildren().add(btn);
primaryStage.setScene(new Scene(root, 300, 250));
primaryStage.show();
}
}
Including a screenshot of the source code just to make sure it is clear to understand.
Happy Coding.
No comments:
Post a Comment