不确定这是否是您要找的...
Button node = new Button();
node.getStyleClass().add("my-new-style-class");
.my-new-style-class {
-fx-padding: 5;
}
Run Code Online (Sandbox Code Playgroud)
这个想法是创建一个临时 stlyesheet 文件,在里面写入新的样式类,将样式表添加到节点的工作表列表中,并添加新的样式类。
这是一个工作示例:
Button button = new Button("My Text");
button.setOnAction(e -> {
try {
// Create a new tempfile that will be removed as the application exits
File tempStyleClass = File.createTempFile("AppXY_TempStyleClass", ".css");
tempStyleClass.deleteOnExit();
// Write the stlye-class inside
try (PrintWriter printWriter = new PrintWriter(tempStyleClass)) {
printWriter.println(".temp-style { -fx-text-fill: red; }");
}
// Add the style-sheet and the style-class to the node
button.getStylesheets().add(tempStyleClass.toURI().toString());
button.getStyleClass().add("temp-style");
} catch (IOException e1) {
e1.printStackTrace();
}
});
Run Code Online (Sandbox Code Playgroud)