Berry
Berry

Reputation: 2298

How to detect a selection on JavaFX TableView when clicking a highlighted item?

I need a way to get the user selection every time a user selects an item on a TableView, even if the item is already selected.

The tableView.getSelectionModel().selectedItemProperty().addListener works when the user selects a different item from the one highlighted, but if the user selects the highlighted item again, it doesn't seem to work.

How would this be fixed?

Upvotes: 1

Views: 10087

Answers (3)

Paweł
Paweł

Reputation: 212

The simplest way what i know:

 yourTableView.setOnMousePressed(e ->{
                if (e.getClickCount() == 2 && e.isPrimaryButtonDown() ){
                    int index = yourTableView.getSelectionModel().getSelectedIndex();
                    System.out.println("" + index);
                }
            });

put it in to constructor or initialize method in your corntroller class... :)

Upvotes: 0

fabian
fabian

Reputation: 82461

If you're only interested in the clicks on the rows, use a custom rowFactory:

TableView<Item> table = ...
EventHandler<MouseEvent> clickListener = evt -> {
    TableRow<Item> row = (TableRow<Item>) evt.getTarget();
    if (!row.isEmpty()) {
        // do something for non-empty rows
        System.out.println("you clicked " + row.getItem());
    }
};

table.setRowFactory(tv -> {
    TableRow<Item> row = new TableRow<>();

    // add click listener to row
    row.setOnMouseClicked(clickListener);

    return row;
});

Upvotes: 0

Kachna
Kachna

Reputation: 2961

you can do this:

tableView.setOnMouseClicked((MouseEvent event) -> {
        if(event.getButton().equals(MouseButton.PRIMARY)){
            System.out.println(tableView.getSelectionModel().getSelectedItem());
        }
    });

the code above doesn't work if you select the highlighted item again using editable table cell

Upvotes: 4

Related Questions