user68883
user68883

Reputation: 838

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

I have a TableView in one of the Tabs of a TabPane. I want to add a click event on the cell, user id , so that when ever the user clicks on a particular user id , i open a new tab with user specific details. how to add event listeners to all the cells in a column ?

<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>

This blog http://java-buddy.blogspot.com/2013/05/detect-mouse-click-on-javafx-tableview.html talks about capturing the click event programmatically, how do I do something similar when using FXML ?

Upvotes: 2

Views: 8051

Answers (1)

James_D
James_D

Reputation: 209684

You need to do this in the controller. Add a fx:id to the table column (say fx:id="userIdColumn"), and then in the controller set a cell factory on the column:

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...

}

Here I am assuming that your table displays objects of some class User that you have created, and that the user id is a String. Obviously you can adjust the types as needed.

Upvotes: 2

Related Questions