gpt4 book ai didi

java - 如何在 Javafx 中将图像添加为组合框中的选项

转载 作者:行者123 更新时间:2023-12-02 09:24:00 26 4
gpt4 key购买 nike

我尝试将图像添加到组合框以将它们显示为选项,但是一旦我选择图像,当下拉列表再次打开以选择它们时,它们就会变成白色。

ImageView img1 = new ImageView(getClass().getResource("item1.png").toExternalForm());
ImageView img2 = new ImageView(getClass().getResource("item2.jpg").toExternalForm());
ImageView img3 = new ImageView(getClass().getResource("item3.jpg").toExternalForm());
img1.setFitHeight(60);
img1.setFitWidth(60);
img1.setPreserveRatio(true);
img2.setFitHeight(60);
img2.setFitWidth(60);
img2.setPreserveRatio(true);
img3.setFitHeight(60);
img3.setFitWidth(60);
img3.setPreserveRatio(true);
combobox.getItems().addAll(img1,img2,img3);

这些选项只能工作一次,当我尝试再次选择它们时,它们会变成白色。

最佳答案

您没有正确设置元素。您需要利用组合框的 setCellFactory() 方法才能正确生成列表项,因为项目预计是相关数据的列表,而不是节点。然后,ListCell 对象可以调用 setGraphic(ImageView),并将列表的该元素更新为指定的图像。

这是我的一个旧项目中的一些示例代码,它实际上是为 ListView 设计的,但工作方式与 ComboBox 完全相同:

pieceData = FXCollections.observableArrayList("Boot", "Car", "Dog", "Hat", "Iron",
"Ship", "Thimble", "Wheelbarrow");
pieceSelection.setItems(pieceData);

pieceSelection.setCellFactory(e -> new ListCell<String>() {
private ImageView view = new ImageView();
@Override
public void updateItem(String name, boolean empty) {
super.updateItem(name, empty);
if(empty) {
setGraphic(null);
}
else {
view.setImage(new Image("whatever the filepath to your image is"));
// Add other set up for ImageView dimensions etc
setGraphic(view);
}
}
});

请记住,这仅显示图像,因为需要调用方法 setText(String) 才能显示任何文本。

正如 kleopatra 所说,您应该阅读基本的 JavaFX 教程,因为此类内容有详细的文档记录并且相对简单。

关于java - 如何在 Javafx 中将图像添加为组合框中的选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58473218/

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