Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use JavaFX FilteredList in a ListView? [closed]

I have a ListView in my application which contains Strings. Now, I want to filter this list by an input field. But all examples about FilteredLists I found are about how to filter a table.

How can I filter a ListView using a FilteredList?

like image 310
Franz Deschler Avatar asked Feb 11 '15 07:02

Franz Deschler


1 Answers

That is rather simple and straightforward:

@Override
public void start(Stage primaryStage) {

    ObservableList<String> data = FXCollections.observableArrayList();
    IntStream.range(0, 1000).mapToObj(Integer::toString).forEach(data::add);

    FilteredList<String> filteredData = new FilteredList<>(data, s -> true);

    TextField filterInput = new TextField();
    filterInput.textProperty().addListener(obs->{
        String filter = filterInput.getText(); 
        if(filter == null || filter.length() == 0) {
            filteredData.setPredicate(s -> true);
        }
        else {
            filteredData.setPredicate(s -> s.contains(filter));
        }
    });


    BorderPane content = new BorderPane(new ListView<>(filteredData));
    content.setBottom(filterInput);

    Scene scene = new Scene(content, 500, 500);
    primaryStage.setScene(scene);
    primaryStage.show();
}
like image 86
eckig Avatar answered Nov 07 '22 08:11

eckig