Placing an image into a JavaFX 2 table

前端 未结 2 1806
灰色年华
灰色年华 2021-01-06 16:12

I\'m trying to do something pretty simple. I want to place an icon in a column for a particular row in a table. If it\'s a folder, display a folder icon. If it\'s a file, di

2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-06 16:57

    Okay so I had a huge dummy moment. Turns out that I had my image url path wrong.

    I did find a site that provides a great example for adding elements for table. This helped me understand everything.

    Now if the 4 different ways I tried before would've worked, I don't know because my image url path was wrong. But anyway here is the link and a code snippet.

    Bottom line was that you need to have the CellValueFactory and the CellFactory. I was attempting to use either or. The updateItem template method in TableCell relies on the value dervied from 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;
        }
    
    });
    

提交回复
热议问题