每个所选项目的JavaFX ComboBox背景颜色

时间:2016-08-04 06:41:51

标签: java javafx combobox javafx-8

我想根据所选项目更改ComboBox的背景。

例如:如果选择第一项,则背景应为绿色,如果选择第二项则为红色。

这可能吗?

4 个答案:

答案 0 :(得分:1)

当然这是可能的。在您使用ListCell的{​​{3}}中创建自定义ComboBox,并根据其中包含的项目使用它来修改Cell的样式。

示例:

public class Item {

    public Item(String value, Color color) {
        this.value = value;
        this.color = color;
    }

    private final String value;
    private final Color color;

    public String getValue() {
        return value;
    }

    public Color getColor() {
        return color;
    }
}
ComboBox<Item> comboBox = new ComboBox<>(FXCollections.observableArrayList(
        new Item("Summer", Color.RED),
        new Item("Winter", Color.CYAN),
        new Item("Spring", Color.LIME),
        new Item("Autumn", Color.BROWN)
));

comboBox.setCellFactory(lv -> new ListCell<Item>(){

    @Override
    protected void updateItem(Item item, boolean empty) {
        super.updateItem(item, empty);

        if (empty || item == null) {
            setBackground(Background.EMPTY);
            setText("");
        } else {
            setBackground(new Background(new BackgroundFill(item.getColor(),
                                                            CornerRadii.EMPTY,
                                                            Insets.EMPTY)));
            setText(item.getValue());
        }
    }

});

comboBox.setButtonCell(comboBox.getCellFactory().call(null));

答案 1 :(得分:1)

如果您只想设置ComboBox本身的颜色而不是下拉列表中ComboBox的项目,您可以在buttonCellProperty之间创建自定义绑定以及ComboBox的{​​{3}}来实现自定义着色。

示例

如果选择了第一个项目,此示例将ComboBox设置为绿色,如果选择了第二个项目,则将其设置为红色,否则保留颜色。

更新: ComboBox的箭头按钮的背景颜色现在也已着色,因为valueProperty方法可用于获取箭头按钮:{ {1}}。

StackPane arrowButton = (StackPane) combo.lookup(".arrow-button");

结果如下:

lookup

备注

1)如果您还想在下拉列表中为项目着色,可以在此处从其他答案中选择解决方案。

2)如果您没有显示ComboBox<String> combo = new ComboBox<>(); combo.setItems(FXCollections.observableArrayList("First", "Second", "Third", "Fourth")); combo.buttonCellProperty().bind(Bindings.createObjectBinding(() -> { int indexOf = combo.getItems().indexOf(combo.getValue()); Color color = Color.TRANSPARENT; switch (indexOf) { case 0: color = Color.GREEN; break; case 1: color = Color.RED; break; default: break; } final Color finalColor = color; // Get the arrow button of the combo-box StackPane arrowButton = (StackPane) combo.lookup(".arrow-button"); return new ListCell<String>() { @Override protected void updateItem(String item, boolean empty) { super.updateItem(item, empty); if (empty || item == null) { setBackground(Background.EMPTY); setText(""); } else { setBackground(new Background(new BackgroundFill(finalColor, CornerRadii.EMPTY, Insets.EMPTY))); setText(item); } // Set the background of the arrow also if (arrowButton != null) arrowButton.setBackground(getBackground()); } }; }, combo.valueProperty())); s但是也能够存储项目颜色的项目,解决方案甚至更短,只需使用所选颜色String方法中的项目,而不是计算自己的颜色。

答案 2 :(得分:0)

 public class Main extends Application {

Random r = new Random();
private class Item {
    Color c;
    String s;
    public Item(Color a,String b){
        c = a;
        s = b;
    }

    @Override
    public String toString() {
        // TODO Auto-generated method stub
        return s;
    }
}

private void addAll(List<String> items){
    for(String s : items){
        box.getItems().add(new Item(Color.WHITE,s));
    }
}

ComboBox<Item> box;

@Override
public void start(Stage primaryStage) {

    Pane p;

    try {
        p = new StackPane();
        box = new ComboBox<Item>();
        box.setMinWidth(100);
        addAll(Font.getFontNames());
        box.setCellFactory(new Callback<ListView<Item>, ListCell<Item>>() {

            @Override
            public ListCell<Item> call(ListView<Item> param) {
                // TODO Auto-generated method stub
                return new ListCell<Item>(){


                    @Override
                    public void updateSelected(boolean selected) {
                        super.updateSelected(selected);
                        if(selected){
                            getItem().c = Color.rgb(r.nextInt(205),
                                    r.nextInt(205), r.nextInt(205), 1);

                        }
                        setStyle("-fx-text-fill: black; -fx-background-color: #" +
                                getItem().c.toString().substring(2)+";");
                    }

                    @Override
                    protected void updateItem(Item item, boolean empty) {
                        // TODO Auto-generated method stub
                        super.updateItem(item, empty);
                        if(empty){
                            return;
                        }
                        setText(item.toString());
                        setStyle("-fx-text-fill: black; -fx-background-color: #" +
                                getItem().c.toString().substring(2)+";");
                    }

                };
            }
        });
        p.getChildren().add(box);
        p.setPrefSize(500, 500);
        Scene scene = new Scene(p);
        scene.getStylesheets().add(getClass().
                getResource("application.css").toExternalForm());
        primaryStage.setScene(scene);
        primaryStage.show();

    } catch(Exception e) {
        e.printStackTrace();
    }
}

答案 3 :(得分:0)

    combobox.valueProperty().addListener(new ChangeListener<String>() {
        @Override
        public void changed(ObservableValue ov, String t, String t1) {
            if (t1.equals("Option 1")) {
               combobox.setStyle(" -fx-background-color: #000000");
            }
            if (t1.equals("Option 2")) {
                combobox.setStyle(" -fx-background-color: #FFFFFF");
            }
        }
    });

你应该能够像上面那样使用基本的更改监听器做一些非常简单的事情,你可能需要刷新页面(我经常只是删除并重新添加组件,以便你可以看到发生的变化)

这是基于你想要选择一个组合框项目然后要改变的方框,而不是每个项目都有一个不同的颜色从开始