将图像放入JavaFX 2表中

我正在尝试做一些非常简单的事情。 我想在表格中的特定行的列中放置一个图标。 如果是文件夹,则显示文件夹图标。 如果是文件,则显示文件图标。

有谁知道如何在JavaFX 2中这样做?

我已经尝试了很多东西,这看起来应该是非常简单的,或者至少是某个地方的例子。

好的,所以我有一个巨大的虚拟时刻。 原来我的图片url路径错了。

我找到了一个网站,它为添加表格元素提供了一个很好的例子。 这有助于我理解一切。

现在,如果我之前尝试过的4种不同的方式都可以工作,我不知道,因为我的图像url路径是错误的。 但无论如何这里是链接和代码片段。

最重要的是你需要拥有CellValueFactoryCellFactory 。 我试图使用其中一个或。 TableCell中的updateItem模板方法依赖于从CellValueFactory提取的值。

http://blog.ngopal.com.np/2011/10/01/tableview-cell-modifiy-in-javafx/

  TableColumn albumArt = new TableColumn("Album Art"); albumArt.setCellValueFactory(new PropertyValueFactory("album")); albumArt.setPrefWidth(200); // SETTING THE CELL FACTORY FOR THE ALBUM ART albumArt.setCellFactory(new Callback,TableCell>(){ @Override public TableCell call(TableColumn param) { TableCell cell = new TableCell(){ @Override public void updateItem(Album item, boolean empty) { if(item!=null){ HBox box= new HBox(); box.setSpacing(10) ; VBox vbox = new VBox(); vbox.getChildren().add(new Label(item.getArtist())); vbox.getChildren().add(new Label(item.getAlbum())); ImageView imageview = new ImageView(); imageview.setFitHeight(50); imageview.setFitWidth(50); imageview.setImage(new Image(MusicTable.class.getResource("img").toString()+"/"+item.getFilename())); box.getChildren().addAll(imageview,vbox); //SETTING ALL THE GRAPHICS COMPONENT FOR CELL setGraphic(box); } } }; System.out.println(cell.getIndex()); return cell; } }); 

如果提供的答案对你不起作用(就像它不适合我),这就是我找到的解决方案(当然你还需要创建tableView并向其中添加列):

 //Create your column that will hold the image private final TreeTableColumn columnImage= new TreeTableColumn("Image"); public void start() { //Set your cellValueFactory to a SimpleObjectProperty //Provided that your class has a method "getImage()" this will work beautifully! columnImage.setCellValueFactory(c-> new SimpleObjectProperty(new ImageView(c.getValue().getValue().getImage()))); }