Risky_91
Risky_91

Reputation: 81

Set JavaFX TableView Item on Mouse click

I have a JavaFX TableView that is populated by a 2D observable list ObservableList<ObservableList<Item>>. I want the user to be able to select an item, and then set that item in the TableView using a mouse click.

Here is the code I have:

@Override 
protected void updateItem(Item item, boolean empty) {
    super.updateItem(item, empty);

    //Various code to set up the custom CellFactory has been removed.

    this.setOnMouseClicked((MouseEvent e) -> {
        Item newItem = getNewItem();
        if (e.getButton() == MouseButton.PRIMARY && newItem != null) {
            // Code to set the underlying data item to the new item
        }
    });

Any help would be greatly appreciated.

Upvotes: 1

Views: 6015

Answers (1)

James_D
James_D

Reputation: 209359

I assume you have a

TableView<ObservableList<Item>> table ;

and a bunch of

TableColumn<ObservableList<Item>, Item> col ;

each of which has a cell factory which is aware of the columnIndex, with the value displayed by the cell given by the columnIndexth element of the list representing the row.

Then you can do

this.setOnMouseClicked((MouseEvent e) -> {
    Item newItem = getNewItem();
    if (e.getButton() == MouseButton.PRIMARY && newItem != null) {
        // Code to set the underlying data item to the new item
        ObservableList<Item> row = (ObservableList<Item>) getTableRow().getItem();
        row.set(columnIndex, newItem);
    }
});

Upvotes: 1

Related Questions