-
-
Save alvareztech/1cfbb4651b863938c07af94304d2a048 to your computer and use it in GitHub Desktop.
JavaFX: Búsqueda en un ListView con FilteredList
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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