javafx经常不通过CSS更改节点的样式 [英] javafx change style of a node frequently not by CSS

查看:427
本文介绍了javafx经常不通过CSS更改节点的样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例是阶段中的3个节点:button,colorpicker和comboBox(用于更改文本大小)。

Example is 3 nodes in stage: button, colorpicker and comboBox(for change text size) .

Button btn = new Button("Change color and size");
ColorPicker colorpicker = new ColorPicker();
ComboBox sizebox = new ComboBox();
sizebox.getItems().addAll("13", "15", "16", "17", "18", "19", "20", "22");

ColorPicker将按客户更改按钮背景颜色,sizebox将按客户更改文本大小。

ColorPicker will change the button background color by customer, and sizebox will change the text size by customer.

colorpicker.setOnAction(e-> btn.setStyle("-fx-background-  color:#"+Integer.toHexString(colorpicker.getValue().hashCode())));
sizebox.setOnAction(e-> btn.setStyle("-fx-font-size:"+sizebox.getValue().toString()));`

当前结果是当我通过colorpicker设置颜色然后设置大小时,colorpicker设置的当前颜色将在更改大小后被删除为默认值。我怎样才能实现这个功能?

Current result is when I set color by colorpicker then to set size, the current color which just set by colorpicker will be remove to default after change size. How can I come true this function?

与场景构建一样,您可以多次更改文本填充但不影响大小,或更改大小但不影响文本填充。

Like Scene Build, you can change the "text fill" many times but not impact size, or change size but not impact "text fill".

推荐答案

创建一个取决于两个控件的值的绑定,并重新计算两个控件的样式,即使只有一个更改:

Create a binding that depends on the values of both controls and recompute the style from both of them even if only one changes:

Button btn = new Button("Change color and size");
ColorPicker colorpicker = new ColorPicker();
ComboBox sizebox = new ComboBox();
sizebox.getItems().addAll("13", "15", "16", "17", "18", "19", "20", "22");

btn.styleProperty().bind(Bindings.createStringBinding(() -> {
    Color color = colorpicker.getValue();
    Object size = sizebox.getValue();

    String style = color == null ? "" : "-fx-background-color:#" + Integer.toHexString(color.hashCode());
    return size == null ? style : style + ";-fx-font-size:" + size;
}, colorpicker.valueProperty(), sizebox.valueProperty()));

这篇关于javafx经常不通过CSS更改节点的样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆