【发布时间】:2020-01-20 09:35:48
【问题描述】:
用户可以选择两个图形(圆形和方形)。 ComboBox 也可能有一个 Empty 选项。 只有将枚举元素添加到 ComboBox 时,才会显示 ComboBox 按钮的图形。
我希望用户只能从两个形状中进行选择,因此我没有添加 Empty 选项作为 ComboBox 的元素。
The problem : when the Empty option is selected, the line does not appear on the Button.
enum Shapes{
Circle, Square, Empty;
}
@Override
public void start(Stage stage) {
ComboBox<Shapes> shapeBox = new ComboBox<>();
shapeBox.setCellFactory(param-> new ShapeListCell());
shapeBox.setButtonCell(new ShapeListCell());
shapeBox.getItems().add(Shapes.Circle);
shapeBox.getItems().add(Shapes.Square);
//shapeBox.getItems().add(Shapes.Empty);
shapeBox.setValue(Shapes.Empty);
Button clearBtn = new Button("Clear selection");
clearBtn.setOnAction(e->shapeBox.setValue(Shapes.Empty));
HBox root = new HBox(shapeBox,clearBtn);
root.setSpacing(10);
Scene scene = new Scene(root, 400,200);
stage.setScene(scene);
stage.show();
}
private class ShapeListCell extends ListCell<Shapes> {
double r = 10;
@Override
public void updateItem(Shapes item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
setGraphic(null);
} else {
setText(item.toString());
switch (item) {
case Circle:
setGraphic(new Circle(r, r, r));
break;
case Empty:
setGraphic(new Line(0, r, r*2, r));
break;
case Square:
setGraphic(new Rectangle(r*2, r*2));
break;
}
}
}
}
当 Empty 添加到 ComboBox 时:
当 Empty 未添加到 ComboBox 时:
我使用java版本“1.8.0_202”
【问题讨论】: