gpt4 book ai didi

列中带有 ImageView 数组的 JavaFX TableView

转载 作者:行者123 更新时间:2023-11-30 06:09:30 24 4
gpt4 key购买 nike

JavaFX TableView 未在 TableColumn 中显示图像列表。有人可以帮助我在 TableColumn 中显示 TableView 中特定条目的多个图像吗?这是代码:

Controller 类具有以下代码:

@Override
public void initialize(URL arg0, ResourceBundle arg1) {
RecordInfo recordInfo;
Image ii;
ObservableList<RecordInfo>list=FXCollections.observableArrayList();
for(int i=1;i<10;i++){
recordInfo=new RecordInfo();

String p=i+".jpg";

ii=new Image(p);
ImageView[] img=new ImageView[3];

img[0]=new ImageView();
img[0].setImage(ii);
img[0].setFitHeight(120);
img[0].setFitWidth(240);

recordInfo.setPic(img);

pic.setCellValueFactory(new PropertyValueFactory<RecordInfo, ImageView[]>("pic"));
list.add(recordInfo);
}
}

虽然 Record 类有:

public class RecordInfo {
private ImageView[] pic;
public ImageView[] getPic() {
return pic;
}
public void setPic(ImageView[] pic) {
this.pic = pic;
}

}

最佳答案

为此,您需要一个自定义的cellFactory。此外,我建议在 RecordInfo 中使用 Image[] 数组来代替:

public class RecordInfo {

private Image[] pic;

public Image[] getPic() {
return pic;
}

public void setPic(Image[] pic) {
this.pic = pic;
}

}
public class ImagesTableCell<T> extends TableCell<T, Image[]> {

private final List<ImageView> imageViews;
private final HBox container;

private ImagesTableCell(List<ImageView> imageViews) {
this.container = new HBox();
this.imageViews = imageViews;
}

private ImageView getOrCreateImageView() {
if (!imageViews.isEmpty()) {
return imageViews.remove(imageViews.size() - 1);
} else {
ImageView iv = new ImageView();
iv.setFitHeight(20);
iv.setFitWidth(20);
return iv;
}
}

@Override
protected void updateItem(Image[] item, boolean empty) {
super.updateItem(item, empty);

ObservableList<Node> children = container.getChildren();
int newLength = (empty || item == null) ? 0 : item.length;

if (newLength < children.size()) {
// remove ImageViews that are not required
for (int i = newLength; i < children.size(); i++) {
ImageView iv = (ImageView) children.get(i);
imageViews.add(iv); // allow reuse of imageviews
iv.setImage(null); // don't prevent garbagecollection of image
}
children.remove(newLength, children.size());
}

// add missing imageviews
for (int i = children.size(); i < newLength; i++) {
children.add(getOrCreateImageView());
}

// fill imageviews
for (int i = 0; i < newLength; i++) {
((ImageView) children.get(i)).setImage(item[i]);
}

setGraphic(newLength == 0 ? null : container);
}

public static <E> Callback<TableColumn<E, Image[]>, TableCell<E, Image[]>> forTableColumn() {
List<ImageView> views = new ArrayList<>();
return c -> new ImagesTableCell<>(views);
}

}
pic.setCellFactory(ImagesTableCell.forTableColumn());

关于列中带有 ImageView 数组的 JavaFX TableView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50582958/

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