控制fx - 额定宽度



我正在使用Controlfx的RatingBar。

我想绑定宽度值,但它不允许是 248 <值。>

@FXML
private Rating vipRating;
        vipRating.prefWidthProperty().bind(ratingVBox.prefWidthProperty());

RatingBar 在 CSS 中有一个按钮选择器的填充值:

.rating > .container > .button {
    -fx-background-color: transparent;
    -fx-background-image: url("unselected-star.png");
    -fx-padding: 16 16; 
    -fx-background-image-repeat: no-repeat;
}

我们应该删除这个填充。

.rating > .container .button {
        -fx-background-size: cover;
        -fx-padding: 0; 
    }

我们还应该将宽度/高度值应用于按钮而不是评级框。

 .rating > .container .button {
            -fx-pref-width: 20 ;
            -fx-pref-height: 20 ;
            -fx-background-size: cover;
            -fx-padding: 0; 
        }

为了使它以编程方式工作,还有另一个未记录的行为:

如果您这样做:

ratingHeigth.bind(mainBorderPane.prefHeightProperty());
    vipRating.styleProperty().bind(Bindings.concat(".rating > .container .button{ -fx-pref-height: ", ratingHeigth.asString(), ";}"));

由于内联样式只是将字符串指定的实际样式应用于调用的节点,setStyle(...):内联样式不包括选择器,因此它不起作用。

所以我们应该在CSS文件中创建一个CSS变量,如下所示:

.rating {
    button-width: 32;
    button-height: 32;
}
 .rating > .container .button {
                -fx-pref-width: button-width;
                -fx-pref-height: button-height;
                -fx-background-size: cover;
                -fx-padding: 0; 
            }

现在,内联样式应应用于新的CSS变量。

ratingWidth.bind(centerPane.prefWidthProperty());
        vipRating.styleProperty().bind(Bindings.concat("button-width: ", ratingWidth.asString(), ";"));

你可以像这样:

DoubleBinding minPrefBinding = Bindings.createDoubleBinding(() -> {
        if(ratingVBox.getPrefWidth() < 248.0){
            return 248.0;
        }
        return ratingVBox.getPrefWidth();
    }, ratingVBox.prefWidthProperty());
 vipRating.prefWidthProperty().bind(minPrefBinding);

调整最小宽度:vipRating.setMinWidth(Region.USE_PREF_SIZE);vipRating.setMinWidth(0);


编辑:

查看 ControlsFX 源,似乎Rating控件使用 PNG 图形作为其外观。这些图标为 32x32 像素,对齐 5 星图标的容器间距为 4。

简单的数学:(32 + 4) * 5 - 4 = 176

176 是此控件可以具有的最小宽度。您可以覆盖 CSS 并删除间距,这会给您另外 16 个像素,因此您最终会得到 160 像素。

演示应用程序显示打印最小尺寸:

@Override
public void start(Stage primaryStage) throws Exception {
    final Rating rating = new Rating();
    final BorderPane pane = new BorderPane(rating);
    pane.setMaxWidth(Region.USE_PREF_SIZE);
    primaryStage.setScene(new Scene(pane));
    primaryStage.show();
    Platform.runLater(()->System.out.println(rating.getWidth()));
}

如果你真的想删除间距,只需添加以下CSS规则:

.rating > .container {
    -fx-spacing: 0;
}

最新更新