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

其中需要自定义 CellFactory

1. 加载图片

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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 中属性加载图片

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
@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绑定属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
...
@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