2016-03-25 56 views
0

我有改变细胞的图标,下面的代码的问题:JavaFX的更改单元格图标

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?

回答

1

TableCell<S, T>延伸Cell<T>而不是Cell<S>。因此对于TableCell<Account, String>updateItem方法正确的签名是

public void updateItem(String item, boolean empty) 

假设你cellValueFactory

new PropertyValueFactory<Account, String>("type") 

返回包含的图片的网址ObservableValue S,你可以使用

ImageView imgVw = new ImageView(item); 

而不是

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

由于传递给updateItem方法的值是包含在由cellValueFactory返回的ObservableValue之一。

+0

如何访问我的对象在updateItem方法中的方法? – uksz

+1

@uksz:看我的编辑。基本上,'cellValueFactory'选择要使用的项目的一部分,'cellFactory'返回的单元格显示该数据(在本例中为图像)。 – fabian

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中加载它。这样的方法可能会有点棘手,因为您可能要小心,不要在用户滚动时动态加载图像。一般来说,如果你只有几百或几千个缩略图,那么上面代码中定义的直接方法就足够了,而不是基于替代缓存的方法。