javafx change style of a node frequently not by CSS

二次信任 提交于 2019-12-12 04:44:22

问题


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 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()));`

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".


回答1:


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()));


来源:https://stackoverflow.com/questions/46379559/javafx-change-style-of-a-node-frequently-not-by-css

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!