【问题标题】:Multiple labels and images in listview javafxlistview javafx中的多个标签和图像
【发布时间】:2018-05-29 05:53:08
【问题描述】:

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

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);
    }
}

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

 void addToShopCart(ActionEvent event) {
    Image partImage = selectedPart.getPicture();
    shopListView.getItems().addAll(selectedPart.getDescription());
    shopListView.setCellFactory(param -> new Cell(partImage));
}

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

【问题讨论】:

标签: java sqlite javafx


【解决方案1】:

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

首先你需要一个类来描述列表中的项目——大概它们是“产品”(因为它是一个购物清单)并且有描述和图像:

class Product {
    final StringProperty description = new SimpleStringProperty(this, "description"); 
    final StringProperty image = new SimpleStringProperty(this, "image"); 

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

接下来,将Cell 类定义为扩展ListCell&lt;Product&gt; - 这意味着item 属性将是Product 类型,item 参数的类型应该是updateItem 方法的类型.
现在,每当更新/更改项目时,您都可以更改描述和图像:

@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 对象。您还可以在多个 ImageView 实例中使用相同的 Image 对象,因此如果多个产品使用相同的图像,这也可能是有益的。

【讨论】:

  • 您还应该将ImageView.image 属性设置为null 以允许垃圾收集器声明图像实例,如果它不再在其他地方引用。此外,使用fitHeightfitWidth 可能会有所帮助。 “(假设可能有理由在设置单元工厂后更改它,但这不是常见的做法,在您的情况下不需要” 这不起作用。已经创建的单元格不是如果您交换工厂,则重新创建。这将导致不同的单元实现无法控制使用...
  • @fabian 我的意思是你几乎不应该多次调用setCellFactory,尽管在极少数情况下它可能是可取的,这可能就是为什么这样做不会引发异常.. . 我想不出一个好的理由,但我也不能肯定地说没有。
  • 感谢您的回答。您提供的链接无济于事。但你的答案可以。还有一个问题:我可以创建 FXML 文件到 listItem 并在 Cell 类中使用它吗?
猜你喜欢
  • 2023-03-17
  • 1970-01-01
  • 2017-03-20
  • 2018-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多