Reputation: 45
Assume that we have a simple Tableview with 3 columns (A, B, C). Each Column contains some data which is not important at the moment.
I wondered if it would be possible to make only a whole column selectable (no matter where the user clicks in the column) and retrieve the ID and/or index of that column selected by the user?
For example, the user clicks somewhere in the area of column B. In that case the whole column should be marked and index 2 should be returned.
Any help would be appreciated ;)
Upvotes: 1
Views: 5792
Reputation: 21799
You can try something like this:
table.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
table.getSelectionModel().setCellSelectionEnabled(true);
table.addEventFilter(MouseEvent.MOUSE_PRESSED, (event) -> {
if(event.isShortcutDown() || event.isShiftDown())
event.consume();
});
table.getFocusModel().focusedCellProperty().addListener((obs, oldVal, newVal) -> {
if(newVal.getTableColumn() != null){
table.getSelectionModel().selectRange(0, newVal.getTableColumn(), table.getItems().size(), newVal.getTableColumn());
System.out.println("Selected TableColumn: "+ newVal.getTableColumn().getText());
System.out.println("Selected column index: "+ newVal.getColumn());
}
});
table.addEventFilter(MouseEvent.MOUSE_PRESSED, (event) -> {
if(event.isShortcutDown() || event.isShiftDown())
event.consume();
});
This snippet:
sets the selectionModeProperty
of the selection model of the TableView
to SelectionMode.MULTIPLE
to make the TableView
able to select more than one row.
sets the cellSelectionEnabledProperty
of the selection model of the TableView
to to true
to make the TableView
able to select cells rather than rows
attaches a listener to the focusedCellProperty
of the focus model of the TableView
which listener prints the TableColumn
of the currently selected cell and selects all of the cell in the selected column
consumes the mouse events on the TableView
if a modifier key is pressed to disable for example Shift + Click selection
Upvotes: 3