我已经实现了一个自定义的TableCell& TableColumn在单元格未编辑时显示超链接。我想为超链接添加setOnAction事件。由于我想重用TableCell,我无法在TableCell updateItem方法中添加代码。有没有办法实现这个?
public class TableColumnHyperlink<S> extends TableColumn<S, String> {
public TableColumnHyperlink (String header) {
super(header);
Callback<TableColumn<S, String>, TableCell<S, String>> hypCellFactory =
(TableColumn<S, String> p) -> new TableCellHyperlink();
setCellFactory(hypCellFactory);
}
}
TableCell实现
public class TableCellHyperlink<S> extends TableCell<S, String> {
private final TextField textField;
private final Hyperlink hyperlink;
public TableCellHyperlink() {
textField = new TextField();
hyperlink = new Hyperlink();
setAlignment(Pos.CENTER_LEFT);
}
@Override
public void startEdit() {
super.startEdit();
createTextField();
setText(null);
setGraphic(textField);
textField.requestFocus();
}
@Override
public void cancelEdit() {
super.cancelEdit();
setText(getItem());
setGraphic(null);
}
@Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty && (getTableRow() == null ? true : getTableRow().isEmpty()));
if (empty) {
setText(null);
setGraphic(null);
} else {
if(isEditing()) {
setText(getString());
setGraphic(textField);
} else {
setText(null);
hyperlink.setText(getString());
setGraphic(hyperlink);
}
}
}
private void createTextField() {
textField.setText(getString());
textField.setMinWidth(this.getWidth() - this.getGraphicTextGap() * 2);
textField.addEventFilter(KeyEvent.KEY_PRESSED, (KeyEvent t) -> {
if (t.getCode() == KeyCode.ENTER) {
commitEdit(textField.getText());
} else if (t.getCode() == KeyCode.ESCAPE) {
cancelEdit();
}
});
}
private String getString() {
return (getItem() != null)?getItem():"";
}
}
答案 0 :(得分:2)
如果事件处理程序实现因实例而异,则需要将事件处理程序(或函数)传递给构造函数。由于您可能需要访问单元格,因此您可以执行类似
的操作public class TableCellHyperlink<S> extends TableCell<S, String> {
private final TextField textField;
private final Hyperlink hyperlink;
public TableCellHyperlink(Consumer<TableCellHyperlink<S> handlerFunction) {
textField = new TextField();
hyperlink = new Hyperlink();
hyperlink.setOnAction(event -> handlerFunction.accept(this));
setAlignment(Pos.CENTER_LEFT);
}
// ...
}
现在你可以做类似
的事情了TableCellHyperlink<MyType> hyperlinkCell = new TableCellHyperlink<>(cell -> {
MyType rowValue = (MyType) cell.getTableRow().getValue(); // getTableRow() returns TableRow, not TableRow<MyType>
String cellValue = cell.getItem();
// implement action
});
显然,你可以移动参数并将其传递给自定义TableColumn构造函数。