Выбрать все только в результатах FilteredList (таблица - javafx) - PullRequest
0 голосов
/ 02 октября 2019

Я обновлял инструмент Java, и у меня возникли проблемы с применением новой функции «Выбрать все» только для отсортированных результатов списка ...

Я думаю, что проблема в том, что я не понимаю, какотфильтрованный список и компаратор работает.

Я могу различать, сортируется ли список или нет, и переключать переменную, т.е. noSearch;но, к сожалению, когда я установил флажок «Выбрать все» в отфильтрованном представлении, он по-прежнему выбирает все роли, хотя я говорю ему выбрать те из отфильтрованного списка (который, вероятно, является всеми ролями, поскольку я не понимаю компаратора. .)

Вот функция wraplist:

    public void wrpLst() { 

        // 1. Wrap the ObservableList in a FilteredList (initially display all data).
        FilteredList<Person> filteredData = new FilteredList<>(myItems, p -> true);

        // 2. Set the filter Predicate whenever the filter changes.
        filterField.textProperty().addListener((observable, oldValue, newValue) -> {
            filteredData.setPredicate(person -> {
        noSearch = 0;
                // If filter text is empty, display all persons.
                if (newValue == null || newValue.isEmpty()) {
          noSearch = 1;
                    return true;
                }
                // Compare first name and last name of every person with filter text.
                String lowerCaseFilter = newValue.toLowerCase();

                if (person.getroleName().toLowerCase().indexOf(lowerCaseFilter) != -1) {
          //noSearch = 0;
                    return true; // Filter matches name.
                }
                return false; // Does not match.
            });
        });

        // 2.5 Set the listener on adname to show department combobox
        adname.textProperty().addListener((observable, oldValue, newValue) -> {
            // If filter text is empty, display all persons.
            if (newValue == null || newValue.isEmpty()) {
                this.department.setVisible(false);
              this.dprLbl.setText("");
                return;
            } else {
                this.department.setVisible(true);
          this.dprLbl.setText("->");
            }
        });

        // 3. Wrap the FilteredList in a SortedList. 
        SortedList<Person> sortedData = new SortedList<>(filteredData);

        // 4. Bind the SortedList comparator to the TableView comparator.
        //    Otherwise, sorting the TableView would have no effect.
        sortedData.comparatorProperty().bind(personTable.comparatorProperty());

        // 5. Add sorted (and filtered) data to the table.
        personTable.setItems(sortedData);
    }

А вот функция selectAll:

    public void allRoles() {
            if (checkbox2.isSelected()) {
        if (noSearch == 0) {
          for (Person srtd : sortedData) {
            srtd.setSelected(checkbox2.isSelected());
          }
        } else {
                  for (Person item : myItems) {
                      item.setSelected(checkbox2.isSelected());
                  }
        }
            }
            // Adding EventHandler to the CheckBox to select/deselect all employees in table.
            checkbox2.setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent event) {
                    // Setting the value in all the employees.
          if (noSearch == 0) {
            for (Person srtd : sortedData) {
              srtd.setSelected(checkbox2.isSelected());
            }
          } else {
            for (Person item : myItems) {
              item.setSelected(checkbox2.isSelected());
            }
          }
                }
            });
            this.checkbox2 = checkbox2;
    }

Я думаю, что происходит при попытке выбрать все, когдав фильтрованном режиме функция selectall входит в функцию noSearch = 1 и продолжает выбирать все роли в ней независимо от того, соответствует ли она входу фильтра.

Я пытался применить нижеприведенное в нем, но получаюошибки при компиляции, потому что я предполагаю, что объект отсортированного списка не имеет метода toLowercase:

          for (Person srtd : sortedData) {
            if (srtd.toLowerCase().indexOf(lowerCaseFilter) != -1) {
                srtd.setSelected(checkbox2.isSelected());
            }
          }

lowerCaseFilter является входом фильтра / поиска txtbox

...