Javafx adding Image in TableView

最后都变了- 提交于 2019-12-01 09:58:12

One of the posible approach for this issue is to create simple class, lets say CustomImage with private ImageView object initialization and its setter and getter. Next, you can use this class to specify TableView<T> and TableColumn<T> generic types, set column's cell value factory, and populate table with your images. Implementation of example CustomImage class and its practical use is shown below:

import javafx.scene.image.ImageView;

public class CustomImage {

    private ImageView image;

    CustomImage(ImageView img) {
        this.image = img;
    }

    public void setImage(ImageView value) {
        image = value;
    }

    public ImageView getImage() {
        return image;
    }
}

Practical implementation:

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class ImageViewInTableView extends Application {

    public Parent createContent() {

        /* layout */
        BorderPane layout = new BorderPane();

        /* layout -> center */
        TableView<CustomImage> tableview = new TableView<CustomImage>();

        /* layout -> center -> tableview */

        /* initialize two CustomImage objects and add them to the observable list */
        ObservableList<CustomImage> imgList = FXCollections.observableArrayList();
        CustomImage item_1 = new CustomImage(new ImageView(new Image("Icon_AddNewPatient.png")));
        CustomImage item_2 = new CustomImage(new ImageView(new Image("Icon_EditPatient.png")));
        imgList.addAll(item_1, item_2);

        /* initialize and specify table column */
        TableColumn<CustomImage, ImageView> firstColumn = new TableColumn<CustomImage, ImageView>("Images");
        firstColumn.setCellValueFactory(new PropertyValueFactory<CustomImage, ImageView>("image"));
        firstColumn.setPrefWidth(60);

        /* add column to the tableview and set its items */
        tableview.getColumns().add(firstColumn);
        tableview.setItems(imgList);

        /* add TableView to the layout */
        layout.setCenter(tableview);
        return layout;
    }

    @Override
    public void start(Stage stage) throws Exception {
        stage.setScene(new Scene(createContent()));
        stage.setWidth(200);
        stage.setHeight(200);
        stage.show();
    }

    public static void main(String args[]) {
        launch(args);
    }
}

And thats how it looks like:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!