Skip to content

Instantly share code, notes, and snippets.

@alvareztech
Created May 3, 2017 17:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alvareztech/1cfbb4651b863938c07af94304d2a048 to your computer and use it in GitHub Desktop.
Save alvareztech/1cfbb4651b863938c07af94304d2a048 to your computer and use it in GitHub Desktop.
JavaFX: Búsqueda en un ListView con FilteredList
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
ObservableList<String> items = FXCollections.observableArrayList("Juan", "Maria", "Pedro", "Mariela", "Juan Pablo");
FilteredList<String> datosFiltradosLista = new FilteredList<String>(items, s -> true);
TextField busquedaTextField = new TextField();
busquedaTextField.setPromptText("Buscar");
busquedaTextField.textProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
String texto = busquedaTextField.getText();
if (texto == null || texto.length() == 0) {
datosFiltradosLista.setPredicate(s -> true);
} else {
datosFiltradosLista.setPredicate(s -> s.contains(texto));
}
}
});
ListView<String> listView = new ListView<String>(datosFiltradosLista);
VBox vBox = new VBox();
vBox.getChildren().add(busquedaTextField);
vBox.getChildren().add(listView);
vBox.setSpacing(20);
vBox.setPadding(new Insets(20, 20, 20, 20));
Scene scene = new Scene(vBox, 400, 400);
primaryStage.setScene(scene);
primaryStage.show();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment