JavaFX TableView: Select the whole TableColumn and get the index

為{幸葍}努か 提交于 2019-12-12 22:56:06

问题


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 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



来源:https://stackoverflow.com/questions/38012247/javafx-tableview-select-the-whole-tablecolumn-and-get-the-index

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!