我在 JavaFX 中使用 fxControls 的切换开关。 我可以通过 CSS 文件覆盖此属性:
.toggle-switch:selected .thumb-area {
-fx-background-color: linear-gradient(to bottom, derive(-fx-text-box-border, -20%), derive(-fx-text-box-border, -30%)), linear-gradient(to bottom, derive(#0b99c9, 30%), #0b99c9);
-fx-background-insets: 0, 1;
}
但是我想通过代码来更改组件中的某些颜色(例如选定模式下的蓝色背景)但是 这不起作用:
String css = ".toggle-switch:selected .thumb-area{-fx-background-color: linear-gradient(to bottom, derive(-fx-text-box-border, -20%), derive(-fx-text-box-border, -30%)),linear-gradient(to bottom, derive(#0b99c9, 30%), #0b99c9);-fx-background-insets: 0, 1;}";
toggleSwitch.setStyle(css);
感谢您的帮助。
最佳答案
我认为您可以使用查找的颜色来实现您想要实现的目标。在您的 CSS 文件中,执行以下操作:
.root {
-my-selected-control-color: #0b99c9 ;
}
然后根据您定义的查找颜色定义所有样式:
.toggle-switch:selected .thumb-area{
-fx-background-color: linear-gradient(to bottom, derive(-fx-text-box-border, -20%), derive(-fx-text-box-border, -30%)),
linear-gradient(to bottom, derive(-my-selected-control-color, 30%), -my-selected-control-color);
-fx-background-insets: 0, 1;
}
您可以根据需要定义任意数量的这些。
现在,如果需要,您只有一个位置可以更改颜色(在 CSS 文件中)。您还可以使用一行代码以编程方式修改此设置:
// assume root is the root of the UI
// you can always retrieve this with Node root = anyNode.getScene().getRoot();
// This will change all occurrences of -my-selected-control-color to
// a bright green:
root.setStyle("-my-selected-control-color: #00b140 ;");
另请参阅this related post .
关于java - 如何通过复杂对象的代码覆盖 JavaFX css,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60621337/