JavaFx向TableViewColumn添加Image

JavaFX 的表格控件使用稍微不同于 Android 和 iOS 中的表格 . 流程上是向 TableView 中 添加列 TableColumn 然后再给列绑定数据 , 再设置 TableView 的数据 , 刷新即可得到可视结果 .

其中需要自定义 CellFactory

1. 加载图片

KiwiId.setCellFactory(new Callback<TableColumn<NewBeautifulKiwi, Integer>, TableCell<NewBeautifulKiwi, Integer>>() {
    @Override
    public TableCell<NewBeautifulKiwi, Integer> call(TableColumn<NewBeautifulKiwi, Integer> param) {
      ...
      TableCell<NewBeautifulKiwi, Integer> cell = new TableCell<NewBeautifulKiwi, Integer>() {
         public void updateItem(Integer item, boolean empty) {
            if (item != null) {
              imageview.setImage(new Image("arrow.png"));
            }
         }
      };
      // Attach the imageview to the cell
      cell.setGraphic(imageview);
      return cell;
    }
 });
 KiwiId.setCellValueFactory(new PropertyValueFactory<NewBeautifulKiwi, Integer>("KiwiId"));

2. 从数据类 NewBeautifulKiwi 中属性加载图片

@Entity(name = "KIWI_TABLE")
public class NewBeautifulKiwi implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int KiwiId;
    private String Kiwi;
    private Image kiwiImage;

    public int getKiwiId() {
        return KiwiId;
    }

    public void setKiwiId(int KiwiId) {
        this.KiwiId = KiwiId;
    }

    public String getKiwi() {
        return Kiwi;
    }

    public void setKiwi(String Kiwi) {
        this.Kiwi = Kiwi;
    }

    public Image getKiwiImage() {
        return kiwiImage;
    }

    public void setKiwiImage(Image kiwiImage) {
        this.kiwiImage = kiwiImage;
    }
}

3. 在 table 中给 tableColumn绑定属性

...
@FXML
private TableColumn<NewBeautifulKiwi, Image> KiwiImageCol;
...
@Override
public void initialize(URL url, ResourceBundle rb) {
    KiwiImageCol.setCellFactory(param -> {
       //Set up the ImageView
       final ImageView imageview = new ImageView();
       imageview.setFitHeight(50);
       imageview.setFitWidth(50);

       //Set up the Table
       TableCell<NewBeautifulKiwi, Image> cell = new TableCell<NewBeautifulKiwi, Image>() {
           public void updateItem(Image item, boolean empty) {
             if (item != null) {
                  imageview.setImage(item);
             }
           }
        };
        // Attach the imageview to the cell
        cell.setGraphic(imageview);
        return cell;
   });
   KiwiImageCol.setCellValueFactory(new PropertyValueFactory<NewBeautifulKiwi, Image>("kiwiImage"));
}

参考资料:

  1. stackoverflow
我来评几句
登录后评论

已发表评论数()

相关站点

+订阅
热门文章