问题
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 ;)
回答1:
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
toSelectionMode.MULTIPLE
to make theTableView
able to select more than one row.sets the cellSelectionEnabledProperty of the selection model of the
TableView
to totrue
to make theTableView
able to select cells rather than rowsattaches a listener to the focusedCellProperty of the focus model of the
TableView
which listener prints theTableColumn
of the currently selected cell and selects all of the cell in the selected columnconsumes the mouse events on the
TableView
if a modifier key is pressed to disable for example Shift + Click selection
来源:https://stackoverflow.com/questions/38012247/javafx-tableview-select-the-whole-tablecolumn-and-get-the-index