问题
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