Can I use setStyle() to directly change a Node's substructure class style?

时间:2015-06-25 18:33:07

标签: java javafx java-8

I have an object that implements a custom ProgressBar. Sometimes I want the bar's track to have a white color and sometimes I want it to be black. I found that can set the default value for it in my .css file by using the following:

.my-bar .track {
    -fx-background-color: bar-default-color;
}

I hoped I could vary that color in the constructor based on passed in value settings. But despite Googling all over for it I have yet to find an example where Node.setStyle() is used to change a Substructure class' style. Calling setStyle("-fx-background-color: desired-color") directly on the ProgressBar object creates odd colors that do not match what I wanted. I'm sure that's because I need to set it on the .track Substructure instead of the parent class. So how do I access and change it via code?

2 个答案:

答案 0 :(得分:4)

您可以使用.trackProgressBar上使用样式final Node track = progressBar.lookup(".track"); track.setStyle("-fx-background-color: desired-color"); 提取节点,然后对其应用样式:

app.get

答案 1 :(得分:2)

不能通过setStyle()直接更改CSS属性,但是(作为查找的替代方法)可以更改CSS属性中使用的颜色,这些颜色在modena.css .root中定义。

因此,对于您的用例,进度条轨道定义为:

.progress-bar > .track {
      -fx-background-color: 
          -fx-shadow-highlight-color,
          linear-gradient(to bottom, derive(-fx-text-box-border, -10%), -fx-text-box-border),
          linear-gradient(to bottom, 
            derive(-fx-control-inner-background, -7%),
            derive(-fx-control-inner-background, 0%),
            derive(-fx-control-inner-background, -3%),
            derive(-fx-control-inner-background, -9%)
          );
    -fx-background-insets: 0, 0 0 1 0, 1 1 2 1;
    -fx-background-radius: 4, 3, 2; /* 10, 9, 8 */
}

此处-fx-shadow-highlight-color-fx-text-box-border-fx-control-inner-background是预定义的颜色。它们可以通过setStyle更改:

progBar.setStyle( "-fx-control-inner-background: aqua; 
                   -fx-text-box-border: red; 
                   -fx-shadow-highlight-color:yellow"
                );