[英]How can i apply more than 1 style to a single node at the same time programmatically
I am creating a calculator in JavaFX. 我正在JavaFX中创建一个计算器。 I have a label with fx:ID #labelResult , styled with css. 我有一个标签为fs:ID #labelResult的css样式。 Now i added keyboard listener to the main pane. 现在,我在主窗格中添加了键盘监听器。 So that when i press Left/Right arrow key i change the background color of the #labelResult to a color from a string bgColors array. 这样,当我按向左/向右箭头键时,我会将#labelResult的背景颜色更改为字符串bgColors数组的颜色。 I also added a functionality to change the labels font size when Upper/Down arrow keys pressed. 当按下向上/向下箭头键时,我还添加了更改标签字体大小的功能。 Now problem is. 现在的问题是。 It seems that i can't have both effects applied at the same time. 看来我不能同时应用两种效果。 So when i have the label's background color changed and i trigger the change font size mechanism the font size effect gets applied to the label while the bg color effect resets. 因此,当我更改了标签的背景颜色并触发了更改字体大小机制时,在重置bg颜色效果时,字体大小效果将应用于标签。 How can i have both effects applied at the same time? 如何同时应用两种效果?
PS : I used the setStyle method to apply the style in both cases in my controller. PS:我使用setStyle方法在两种情况下都在控制器中应用样式。
CSS (before applying styles in my controller)
#labelRESULT {
-fx-background-color: rgba(59, 74, 107, 0.8);
-fx-font-size: 45px;
-fx-text-fill: #fff;
}
Controller.java Controller.java
@FXML
private Label labelRESULT;
@FXML
private void handleKeys(KeyEvent event) {
int size = 45;
String keyPressed = event.getCode().toString().toUpperCase();
switch (keyPressed) {
case "RIGHT":
labelRESULT.setStyle("-fx-bg-color: #" + bgColors[1]);
break;
case "UP":
labelRESULT.setStyle("-fx-font-size: " + (size + 2) + "px;");
break;
}
}
Image of what happens: http://imgh.us/javafx-calc.png 发生的情况的图片: http : //imgh.us/javafx-calc.png
1- before applying styles programatically 1-以编程方式应用样式之前
2- after changing bg color of the label 2-更改标签的bg颜色后
3- after changing font size of the label while bg color is changed 3-在改变背景颜色的同时更改标签的字体大小后
You can just add/switch css-classes to your nodes. 您可以仅将css类添加/切换到节点。
JavaFXUtils.addClasses(node, "my-class-for-font");
JavaFXUtils.removeClasses(node, "my-class-for-color");
Maybe it helps if you concat the result of getStyle() (ie bgColor) with the additional style (ie fontSize) and then use setStyle() again? 如果将getStyle()(即bgColor)的结果与其他样式(即fontSize)合并,然后再次使用setStyle(),这可能会有所帮助?
EDIT this would be another option (set the flag to true or false at the correct place): 编辑这将是另一个选项(在正确的位置将标志设置为true或false):
labelRESULT.pseudoClassStateChanged(PseudoClass.getPseudoClass("left-right-pressed"), flag);
labelRESULT.pseudoClassStateChanged(PseudoClass.getPseudoClass("up-down-pressed"), flag);
and define a custom pseudo class in your css: 并在CSS中定义一个自定义伪类:
:left-right-pressed {
-fx-background-color: yellow;
}
:up-down-pressed {
-fx-font-size: 14;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.