JavaFX将单元格更改为图标

时间:2016-03-25 08:44:03

标签: javafx javafx-8

使用以下代码将单元格更改为图标时出现问题:

    TableColumn typeCol = new TableColumn("Account Type");
           typeCol.setCellFactory(new Callback<TableColumn<Account, String>, TableCell<Account, String>>() {
        @Override
        public TableCell<Account, String> call(TableColumn<Account, String> param) {
            TableCell<Account,String> cell = new TableCell<Account, String>(){
                @Override
                public void updateItem(Account item, boolean empty){
                    if (item != null){
                        VBox vb = new VBox();
                        vb.setAlignment(Pos.CENTER);
                        ImageView imgVw = new ImageView(item.getTypeIcon());
                        imgVw.setFitHeight(10);
                        imgVw.setFitWidth(10);
                        vb.getChildren().addAll(imgVw);
                        setGraphic(vb);
                    }
                }
            };
            return cell;
        }
    });
    typeCol.setMinWidth(100);
    typeCol.setCellValueFactory(
            new PropertyValueFactory<Account, String>("type"));

这里的问题是,由于某种原因,我得到'方法不会覆盖或实现超类型的方法'的错误。任何idaes?

2 个答案:

答案 0 :(得分:1)

TableCell<S, T>扩展Cell<T>,而非Cell<S>。因此,TableCell<Account, String> public void updateItem(String item, boolean empty) 方法的正确签名是

cellValueFactory

假设您的new PropertyValueFactory<Account, String>("type")

ObservableValue

返回包含图片网址的ImageView imgVw = new ImageView(item); ,您可以使用

ImageView imgVw = new ImageView(item.getTypeIcon());

而不是

updateItem

由于传递给ObservableValue方法的值是cellValueFactory返回的GCD中包含的值。

答案 1 :(得分:1)

将图像放入表格单元格的示例代码:

import javafx.scene.control.*;
import javafx.scene.image.*;

public class ImageTableCell<S> extends TableCell<S, Image> {
    private final ImageView imageView = new ImageView();

    public ImageTableCell() {
        setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
    }

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

        if (empty || item == null) {
            imageView.setImage(null);
            setText(null);
            setGraphic(null);
        }

        imageView.setImage(item);
        setGraphic(imageView);
    }
}

如果您的表格不代表数百万项,这将正常工作。如果您有许多项目并且无法将所有潜在图像保存在内存中,那么您需要一个TableCell而不是TableCell,其中字符串只是图像的URL而不是实际的图像数据本身。然后你将保留一个LRU缓存的图像数据,你将在updateItem中更新,从缓存中获取图像数据(如果它在那里),否则从URL加载它。这样的方法可能会有点棘手,因为您可能要小心不要在用户滚动时进行过多的动态图像加载。通常,如果您只有几百或几千个缩略图,那么上面代码中定义的直接方法就足够了,而不是基于备用缓存的方法。