How to Override Sorting Behavior in TableView

My TableView populates data from the database. When the user clicks on the column heading, he sorts the data based on this. This feature is not available. However, I have too many entries to fill in at a time. Say I have 1000 records, and the table only shows 500. When I sort it based on a column, it only closes the 500 already filled records.

I would like to override the sorting behavior, so when the user clicks the column heading, he reloads the data from the database and provides the necessary information for the "order by" clause in the query. My problem is that I do not know

  • How to disable existing sorting behavior. I can set the column sort property to false, but I'm afraid the header will not be clickable.
  • How to connect a listener to listen for a column header click event. Is the tableView.getSortOrder () method true? AddListener () is correct?
+4
source share
1 answer

I have an ugly solution that solves only half of the problem. I can attach a listener to the column header click event, but I cannot remove the default sort behavior of the TableView.

private void initTable() { ... ... //listen to sorting type (ASC/DESC) change SortTypeChangeListener sortTypeChangeListener = new SortTypeChangeListener(); clmName.sortTypeProperty().addListener(sortTypeChangeListener); clmGender.sortTypeProperty().addListener(sortTypeChangeListener); reload(); //listen to sortorder change tblMember.getSortOrder().addListener(new ListChangeListener<TableColumn<VOMember, ?>>() { @Override public void onChanged(Change<? extends TableColumn<VOMember, ?>> change) { reload(); } }); } private void reload() { /** * Get sorted columns and sorting versus (ASC/DESC) */ List<String> lstSortedColumn = new ArrayList<String>(); List<String> lstSortedType = new ArrayList<String>(); for (TableColumn<VOMember, ?> tc : tblMember.getSortOrder()) { PropertyValueFactory valFactory = (PropertyValueFactory) tc.getCellValueFactory(); valFactory.getProperty(); lstSortedColumn.add(valFactory.getProperty()); lstSortedType.add(tc.getSortType().name()); } /** * Retrieve data from database. Pass the sorting information */ List<VOMember> lstMember = controller.retrieve(lstSortedColumn, lstSortedType); ObservableList<VOMember> data = FXCollections.observableList(lstMember); tblMember.setItems(data); } class SortTypeChangeListener implements InvalidationListener { @Override public void invalidated(Observable o) { /** * If the column is not in sortOrder list, just ignore. * It avoids intermittent duplicate reload() calling */ TableColumn col = (TableColumn) ((SimpleObjectProperty) o).getBean(); if (!tblMember.getSortOrder().contains(col)) { return; } reload(); } } 

I would like to hear your opinion / comment on this.

+1
source

Source: https://habr.com/ru/post/1435741/


All Articles