如何为 Tableview 中 table 列的单元格设置点击事件?

How to set click event for a cell of a table column in a Tableview?

我在 TabPane 的其中一个选项卡中有一个 TableView。我想在单元格 user id 上添加一个点击事件,这样每当用户点击特定的 user id 时,我都会打开一个包含用户特定详细信息的新选项卡。如何将事件侦听器添加到列中的所有单元格?

<TableView fx:controller="tableViewController"
    fx:id="tableViewTable" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8">
    <columnResizePolicy>
        <TableView fx:constant="CONSTRAINED_RESIZE_POLICY" />
    </columnResizePolicy>
    <columns>
        <TableColumn text="First Name">
            <cellValueFactory>
                <PropertyValueFactory property="firstName" />
            </cellValueFactory>
        </TableColumn>
        <TableColumn text="Last Name">
            <cellValueFactory>
                <PropertyValueFactory property="lastName" />
            </cellValueFactory>
        </TableColumn>
        <TableColumn text="User Id">
            <cellValueFactory>
                <PropertyValueFactory property="userId" />
            </cellValueFactory>
        </TableColumn>
    </columns>
</TableView>

这篇博客 http://java-buddy.blogspot.com/2013/05/detect-mouse-click-on-javafx-tableview.html 讨论了如何以编程方式捕获点击事件,我如何在使用 FXML 时做类似的事情?

您需要在控制器中执行此操作。在table列中添加一个fx:id(比如说fx:id="userIdColumn"),然后在controller中在该列上设置一个cell factory:

public class TableViewController {

    @FXML
    private TableColumn<User, String> userIdColumn ;

    public void initialize() {
        userIdColumn.setCellFactory(tc -> {
            TableCell<User, String> cell = new TableCell<User, String>() {
                @Override
                protected void updateItem(String item, boolean empty) {
                    super.updateItem(item, empty) ;
                    setText(empty ? null : item);
                }
            };
            cell.setOnMouseClicked(e -> {
                if (! cell.isEmpty()) {
                    String userId = cell.getItem();
                    // do something with id...
                }
            };
            return cell ;
        });

        // other initialization code...
    }

    // other controller code...

}

这里我假设你的 table 显示你创建的一些 class User 的对象,并且用户 ID 是 String。显然你可以根据需要调整类型。