Reputation: 83
I have a TableView, where I need to enable the selection of any cells(one at a time). For now, I use this code:
tableView.getSelectionModel().selectedItemProperty().addListener(new ChangeListener() {
@Override
public void changed(ObservableValue observableValue, Object oldValue, Object newValue) {
if(tableView.getSelectionModel().getSelectedItem() != null)
{
TableView.TableViewSelectionModel selectionModel = tableView.getSelectionModel();
ObservableList selectedCells = selectionModel.getSelectedCells();
TablePosition tablePosition = (TablePosition) selectedCells.get(0);
String val = (String)tablePosition.getTableColumn().getCellData(newValue);
System.out.println("Selected Value: " + val);
selectionTextField.appendText(val);
}
}
});
The problem is, I can't get the values of different cells in the same row after each other. I think it's because it's the same row, the selection listener is not triggered. I tried clearSelection(), but then I get out of bounds exception, and I read somewhere that I cant change the table model in the same listener. Any tips?
Thank you.
Upvotes: 1
Views: 4835
Reputation: 209684
If you are using cell selection instead of row selection (in other words, if you have called tableView.getSelectionMode().setCellSelectionEnabled(true);
), then you should observe the list of selected cells instead of the selectedItem
property. The selectedItem
property only indicates the row that is selected, so it only changes if you select a new row.
ObservableList<TablePosition> selectedCells = table.getSelectionModel().getSelectedCells() ;
selectedCells.addListener((ListChangeListener.Change<? extends TablePosition> change) -> {
if (selectedCells.size() > 0) {
TablePosition selectedCell = selectedCells.get(0);
TableColumn column = selectedCell.getTableColumn();
int rowIndex = selectedCell.getRow();
Object data = column.getCellObservableValue(rowIndex).getValue();
}
});
Upvotes: 4