2016-03-25 54 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中加載它。這樣的方法可能會有點棘手,因爲您可能要小心,不要在用戶滾動時動態加載圖像。一般來說,如果你只有幾百或幾千個縮略圖,那麼上面代碼中定義的直接方法就足夠了,而不是基於替代緩存的方法。