gpt4 book ai didi

java - 如何将图像工具提示添加到 JavaFX 中的 ComboBox 项目?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:37:49 25 4
gpt4 key购买 nike

我想为 ComboBox 中的每个项目添加一张照片,这样当用户将鼠标悬停在 ComboBox 中该项目的名称上时,该项目的照片将显示。

这是我的代码:

    lights.setConverter(new StringConverter<Light>() {
@Override
public String toString(Light object) {
return object.getName();
}

@Override
public Light fromString(String string) {
return null;
}
});



lights.setItems(FXCollections.observableArrayList
(new Light ("Incandescent", 5.23),
new Light ("Halogen", 5.75),
new Light ("fluorescent",7.29),
new Light ("Compact fluorescent bulbs",4.83),
new Light ("LED",4.83)));


lights.setPromptText("Please select a light");
lights.setPrefWidth(100);


lights.valueProperty().addListener((obs, oldVal, newVal) -> {
String selectionText = "The price for the " + newVal.getName() + " light is : $" + newVal.getPrice();
lightNamePrice.setText(selectionText);
});

private class Light {
private String name;
private Double price;

private Double getPrice() {
return price;
}

private String getName() {
return name;
}

private Light(String name, Double price) {
this.name = name;
this.price = price;

}

}

有人有什么想法吗?我是 JavaFX 的新手,所以我可以获得任何帮助。

最佳答案

你可以使用 setCellFactory ComboBox 的方法以返回 ListCell 的方式自定义下拉列表中项目的呈现。其中有一个 Tooltip 附加为 ListCellControl 的子类,因此它提供了 setTooltip方法。

示例

我已经更新了 Light 类,让这个类的每个实例都能拥有自己的图像:

private class Light {
private String name;
private Double price;
private Image image;

public Image getImage() {
return image;
}

private Double getPrice() {
return price;
}

private String getName() {
return name;
}

private Light(String name, Double price, Image image) {
this.name = name;
this.price = price;
this.image = image;
}
}

然后我更新了填充数据的代码以使用(相同的)Image:

Image image =  new Image(getClass().getResource("light.png").toExternalForm(), 100, 100, true, true);

lights.setItems(FXCollections.observableArrayList
(new Light ("Incandescent", 5.23, image),
new Light ("Halogen", 5.75, image),
new Light ("fluorescent",7.29, image),
new Light ("Compact fluorescent bulbs",4.83, image),
new Light ("LED",4.83, image)));

最后是细胞工厂的更新:

lights.setCellFactory(param -> {
return new ListCell<Light>() {

@Override
public void updateItem(Light item, boolean empty) {
super.updateItem(item, empty);

if (item != null) {
setText(item.getName());

// Add the Tooltip with the image of the current item
Tooltip tt = new Tooltip();
tt.setGraphic(new ImageView(item.getImage()));

setTooltip(tt);
} else {
setText(null);
setTooltip(null);
}
}
};
});

结果:

enter image description here

您还可以查看有关图像工具提示的问题:How to show Image as tooltip in JavaFX?

关于java - 如何将图像工具提示添加到 JavaFX 中的 ComboBox 项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38738701/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com