英文:
How to reference cell data on CellFactory?
问题
我有一个TableView
,其中最后一列是一个“操作”列,包含一个自定义的ActionBox
对象,其中包含用于多个操作的按钮。为了向这个ActionBox
添加行为,我需要传递一个Data
对象给它。然而,我不知道如何引用这个对象。
我假设对象的引用在Void item
中,所以我尝试将所有出现的Void
替换为Data
,并使用setGraphic(new ActionBox(item));
,但这导致了一个空指针异常,所以我认为这不是正确的方法。那么,在CellFactory上下文中如何引用行的数据呢?
英文:
I have a TableView
where the last column is an "Action" column, containing a custom ActionBox
object, with buttons for several actions. To add behaviour to this ActionBox
, I need to pass a Data
object to it. However, I don't know how to reference the object.
class TableViewWithActionColumn() {
@FXML TableColumn<Data, Void> actionColumn;
public TableViewWithActionColumn() {
// Code for loading custom component...
}
@FXML
public void initialize() {
populateActionColumn();
}
private void populateActionColumn() {
Callback<TableColumn<Data, Void>, TableCell<Data, Void>> cellFactory = new Callback<TableColumn<Data, Void>, TableCell<Data, Void>>() {
@Override
public TableCell<Data, Void> call(final TableColumn<Data, Void> param) {
return new TableCell<Data, Void>() {
private final ActionBox actionBox = new ActionBox();
@Override
public void updateItem(Void item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setGraphic(null);
} else {
setGraphic(actionBox);
}
}
};
}
};
actionColumn.setCellFactory(cellFactory);
}
}
I assumed that the reference to the object was in Void item
, so I tried replacing all occurrences of Void
with Data
, and doing setGraphic(new ActionBox(item));
, but this led to a NullPointerException, so I suppose that's not the right way to do it. So, how do I reference row's data in CellFactory context?
答案1
得分: 3
TableCell
有一个getTableRow()
方法,它可以获取包含该单元格的TableRow
的引用。TableRow
本身也是一个单元格实现,因此您可以调用它的getItem()
方法来获取行所代表的数据。
在上下文中(并且去除您的代码中所有不必要的模板代码):
private void populateActionColumn() {
actionColumn.setCellFactory(col -> new TableCell<Data, Void>() {
private final ActionBox actionBox = new ActionBox();
@Override
public void updateItem(Void item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setGraphic(null);
} else {
Data rowData = getTableRow().getItem();
// ... 类似于:actionBox.setData(rowData) ;
setGraphic(actionBox);
}
}
});
}
英文:
TableCell
has a getTableRow()
method, that gives you a reference to the TableRow
that contains the cell. The TableRow
is itself a cell implementation, so you can call its getItem()
method to get the data represented by the row.
In context (and removing all the unnecessary boilerplate from your code):
private void populateActionColumn() {
actionColumn.setCellFactory(col -> new TableCell<Data, Void>() {
private final ActionBox actionBox = new ActionBox();
@Override
public void updateItem(Void item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setGraphic(null);
} else {
Data rowData = getTableRow().getItem();
// ... something like: actionBox.setData(rowData) ;
setGraphic(actionBox);
}
}
});
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论