首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >listview javafx中的多个标签和图像

listview javafx中的多个标签和图像
EN

Stack Overflow用户
提问于 2018-05-29 05:53:08
回答 1查看 988关注 0票数 0

我想要创建多个标签和图像的listView项目。我创建了一个单元格类:

代码语言:javascript
复制
public class Cell extends ListCell<String> {
private HBox hBox;
private Label description;
private Pane pane;
private ImageView imageView;
private Image deleteImage;
private JFXButton delete;

public Cell() {
    super();
    this.hBox = new HBox();
    this.description = new Label();
    this.pane = new Pane();
    this.delete = new JFXButton("delete");

    this.hBox.getChildren().addAll(description, pane, delete);
    HBox.setHgrow(pane, Priority.ALWAYS);
    delete.setOnAction(event -> getListView().getItems().remove(getItem()));
}

@Override
protected void updateItem(String item, boolean empty) {
    super.updateItem(item, empty);
    setText(null);
    setGraphic(null);

    if (item != null && !empty) {
        description.setText(item);
        setGraphic(hBox);
    }
}

这是我的控制器代码的一部分:

代码语言:javascript
复制
 void addToShopCart(ActionEvent event) {
    Image partImage = selectedPart.getPicture();
    shopListView.getItems().addAll(selectedPart.getDescription());
    shopListView.setCellFactory(param -> new Cell(partImage));
}

选择了我的自定义类,它有一个图像。但是现在我不知道如何向这些标签发送文本,因为updateItem()方法只得到一个字符串。关于图像,我想对每个项目分别设置不同的图像。我试图发送到构造函数,但是所有的图像都是相同的。我正在使用MVC,我也可以使用代码。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-05-29 06:34:51

听起来,列表项不仅仅是字符串,所以您的模型应该是一个更专门的类。取决于它的复杂程度,您甚至可能希望使用TableView,但是现在让我们假设您只有一个名称和一个图像,并且希望使用一个ListView

首先,您需要一个类来描述列表中的项目--假设它们是“产品”(因为它是购物列表),并具有描述和图像:

代码语言:javascript
复制
class Product {
    final StringProperty description = new SimpleStringProperty(this, "description"); 
    final StringProperty image = new SimpleStringProperty(this, "image"); 

    // add getters, property-getters and setters...
}

接下来,将Cell类定义为扩展ListCell<Product> --这意味着item属性将是Product类型,这应该是updateItem方法的item参数的类型。

现在,每当一个项被更新/更改时,您都可以同时更改目录和图像:

代码语言:javascript
复制
@Override
protected void updateItem(Product item, boolean empty) {
    super.updateItem(item, empty);
    setText(null);
    setGraphic(null);

    if (item != null && !empty) {
        description.setText(item.getDescription());
        imageView.setImage(...);
        setGraphic(hBox);
    }
}

添加项时,使用适当的描述和图像创建一个新的Product实例,并将其添加到列表中。请注意,无需每次添加项时调用setCellFactory --应该在初始化期间调用它一次(假设可能有理由在设置了单元工厂之后更改它,但这不是常见的做法,在您的情况下也不需要)。

注意:加载图像可能很慢(取决于图像大小),因此您可能希望缓存或预加载实际的Image对象。您还可以在多个Image实例中使用相同的ImageView对象,因此,如果多个产品使用相同的映像,这也可能是有益的。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50577176

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档