Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create search TextField field to search in a javafx tableview

Say I have a TableView with many columns, and I want to add a search field to filter rows that fit certain criteria, search by name as an example . thank you

like image 682
Day Dreamer Avatar asked Jun 01 '17 22:06

Day Dreamer


People also ask

What is TableView in JavaFX?

The TableView class provides built-in capabilities to sort data in columns. Users can alter the order of data by clicking column headers. The first click enables the ascending sorting order, the second click enables descending sorting order, and the third click disables sorting. By default, no sorting is applied.

How do you filter a table view?

Click a cell in the range or table that you want to filter. On the Data tab, click Filter. in the column that contains the content that you want to filter.

What is TextField in JavaFX?

TextField class is a part of JavaFX package. It is a component that allows the user to enter a line of unformatted text, it does not allow multi-line input it only allows the user to enter a single line of text. The text can then be used as per requirement.


1 Answers

Say you have a TableView called myTable filled with myObject Objects. Create a TextField, in this case I named it filterField, so here is a simple implementation.

FilteredList<myObject> filteredData = new FilteredList<>(data, p -> true);

        // 2. Set the filter Predicate whenever the filter changes.
        filterField.textProperty().addListener((observable, oldValue, newValue) -> {
            filteredData.setPredicate(myObject -> {
                // If filter text is empty, display all persons.
                if (newValue == null || newValue.isEmpty()) {
                    return true;
                }

                // Compare first name and last name field in your object with filter.
                String lowerCaseFilter = newValue.toLowerCase();

                if (String.valueOf(myObject.getFirstName()).toLowerCase().contains(lowerCaseFilter)) {
                    return true;
                    // Filter matches first name.

                } else if (String.valueOf(myObject.getLastName()).toLowerCase().contains(lowerCaseFilter)) {
                    return true; // Filter matches last name.
                } 

                return false; // Does not match.
            });
        });

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

        // 4. Bind the SortedList comparator to the TableView comparator.
        sortedData.comparatorProperty().bind(myTable.comparatorProperty());
        // 5. Add sorted (and filtered) data to the table.
        myTable.setItems(sortedData);
like image 173
Ammar Akouri Avatar answered Sep 28 '22 14:09

Ammar Akouri