我创建了一个组合框并向其中添加了标签,这样我就可以使用带有图标的文本,但在选择项目后图标消失,我做错了什么?
选择之前:
选择后:
ObservableList<Label> booruChoices = FXCollections.observableArrayList();
booruChoices.add(new Label("Gelbooru", new ImageView("https://gelbooru.com/favicon.ico")));
booruChoices.add(new Label("Danbooru", new ImageView("https://i.imgur.com/7ek8bNs.png")));
booruSelector.getItems().addAll(booruChoices);
booruSelector.setCellFactory(param -> {
return new ListCell<Label>() {
@Override
public void updateItem(Label item, boolean empty) {
super.updateItem(item, empty);
if (item != null) {
setGraphic(item.getGraphic());
setText(item.getText());
}
}
};
});
最佳答案
第一个答案不是你想要的,我的错误。
您对 ComboBox
中的单元格和 ComboBox
的按钮使用相同的 ImageView
。一个ImageView
只能显示在一个地方。
您需要为 ComboBox 中的每个单元格创建一个图形节点。对于 ComboBox
来说,Label
不是一个好的项目类型,因为它表示 UI 节点而不是数据对象。
以下是保存数据的类的示例:
public class MyData {
private String name;
private Image image;
public MyData(String name, String imageUrl) {
this.name = name;
this.image = new Image(imageUrl);
}
public String getName() {
return name;
}
public Image getImage() {
return image;
}
}
然后您可以使用该类创建一个ComboBox
:
ComboBox<MyData> comboBox = new ComboBox<>();
MyData data1 = new MyData("Gelbooru", "https://gelbooru.com/favicon.ico");
MyData data2 = new MyData("Danbooru", "https://i.imgur.com/7ek8bNs.png");
comboBox.getItems().addAll(data1, data2);
comboBox.setCellFactory(param -> new ListCell<>() {
final ImageView graphicNode = new ImageView();
@Override
protected void updateItem(MyData item, boolean empty) {
super.updateItem(item, empty);
if (item == null || empty) {
setText(null);
setGraphic(null);
graphicNode.setImage(null);
} else {
setText(item.getName());
graphicNode.setImage(item.getImage());
setGraphic(graphicNode);
}
}
});
关于java - 选择项目后组合框中的图像消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59841920/