Skip to content

Instantly share code, notes, and snippets.

@jesuino
Last active August 16, 2024 08:31
Show Gist options
  • Save jesuino/56de77be529e68384175 to your computer and use it in GitHub Desktop.
Save jesuino/56de77be529e68384175 to your computer and use it in GitHub Desktop.
A simple auto complete solution for combo box
import java.util.stream.Stream;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.Event;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Tooltip;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.stage.Window;
/**
*
* Uses a combobox tooltip as the suggestion for auto complete and updates the
* combo box itens accordingly <br />
* It does not work with space, space and escape cause the combobox to hide and
* clean the filter ... Send me a PR if you want it to work with all characters
* -> It should be a custom controller - I KNOW!
*
* @author wsiqueir
*
* @param <T>
*/
public class ComboBoxAutoComplete<T> {
private ComboBox<T> cmb;
String filter = "";
private ObservableList<T> originalItems;
public ComboBoxAutoComplete(ComboBox<T> cmb) {
this.cmb = cmb;
originalItems = FXCollections.observableArrayList(cmb.getItems());
cmb.setTooltip(new Tooltip());
cmb.setOnKeyPressed(this::handleOnKeyPressed);
cmb.setOnHidden(this::handleOnHiding);
}
public void handleOnKeyPressed(KeyEvent e) {
ObservableList<T> filteredList = FXCollections.observableArrayList();
KeyCode code = e.getCode();
if (code.isLetterKey()) {
filter += e.getText();
}
if (code == KeyCode.BACK_SPACE && filter.length() > 0) {
filter = filter.substring(0, filter.length() - 1);
cmb.getItems().setAll(originalItems);
}
if (code == KeyCode.ESCAPE) {
filter = "";
}
if (filter.length() == 0) {
filteredList = originalItems;
cmb.getTooltip().hide();
} else {
Stream<T> itens = cmb.getItems().stream();
String txtUsr = filter.toString().toLowerCase();
itens.filter(el -> el.toString().toLowerCase().contains(txtUsr)).forEach(filteredList::add);
cmb.getTooltip().setText(txtUsr);
Window stage = cmb.getScene().getWindow();
double posX = stage.getX() + cmb.getBoundsInParent().getMinX();
double posY = stage.getY() + cmb.getBoundsInParent().getMinY();
cmb.getTooltip().show(stage, posX, posY);
cmb.show();
}
cmb.getItems().setAll(filteredList);
}
public void handleOnHiding(Event e) {
filter = "";
cmb.getTooltip().hide();
T s = cmb.getSelectionModel().getSelectedItem();
cmb.getItems().setAll(originalItems);
cmb.getSelectionModel().select(s);
}
}
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class ComboBoxAutoCompleteTest extends Application {
private static final String[] LISTA = { "Abacate", "Abacaxi", "Ameixa", "Amora", "Araticum", "Atemoia", "Avocado",
"Banana prata", "Caju", "Cana descascada", "Caqui", "Caqui Fuyu", "Carambola", "Cereja", "Coco verde",
"Figo", "Figo da Índia", "Framboesa", "Goiaba", "Graviola", "Jabuticaba", "Jambo", "Jambo rosa", "Jambolão",
"Kino (Kiwano)", "Kiwi", "Laranja Bahia", "Laranja para suco", "Laranja seleta", "Laranja serra d’água",
"Laranjinha kinkan", "Lichia", "Lima da pérsia", "Limão galego", "Limão Taiti", "Maçã argentina",
"Maçã Fuji", "Maçã gala", "Maçã verde", "Mamão formosa", "Mamão Havaí", "Manga espada", "Manga Haden",
"Manga Palmer", "Manga Tommy", "Manga Ubá", "Mangostim", "Maracujá doce", "Maracujá para suco", "Melancia",
"Melancia sem semente", "Melão", "Melão Net", "Melão Orange", "Melão pele de sapo", "Melão redinha",
"Mexerica carioca", "Mexerica Murcote", "Mexerica Ponkan", "Mirtilo", "Morango", "Nectarina",
"Nêspera ou ameixa amarela", "Noni", "Pera asiática", "Pera portuguesa", "Pêssego", "Physalis", "Pinha",
"Pitaia", "Romã", "Tamarilo", "Tamarindo", "Uva red globe", "Uva rosada", "Uva Rubi", "Uva sem semente",
"Abobora moranga", "Abobrinha italiana", "Abobrinha menina", "Alho", "Alho descascado",
"Batata baroa ou cenoura amarela", "Batata bolinha", "Batata doce", "Batata inglesa", "Batata yacon",
"Berinjela", "Beterraba", "Cebola bolinha", "Cebola comum", "Cebola roxa", "Cenoura", "Cenoura baby",
"Couve flor", "Ervilha", "Fava", "Gengibre", "Inhame", "Jiló", "Massa de alho", "Maxixe", "Milho",
"Pimenta biquinho fresca", "Pimenta de bode fresca", "Pimentão amarelo", "Pimentão verde",
"Pimentão vermelho", "Quiabo", "Repolho", "Repolho roxo", "Tomate cereja", "Tomate salada",
"Tomate sem acidez", "Tomate uva", "Vagem", "Agrião", "Alcachofra", "Alface", "Alface americana",
"Almeirão", "Brócolis", "Broto de alfafa", "Broto de bambu", "Broto de feijão", "Cebolinha", "Coentro",
"Couve", "Espinafre", "Hortelã", "Mostarda", "Rúcula", "Salsa", "Ovos brancos", "Ovos de codorna",
"Ovos vermelhos" };
public static void main(String[] args) {
launch();
}
@Override
public void start(Stage stage) throws Exception {
ComboBox<String> cmb = new ComboBox<>();
cmb.setTooltip(new Tooltip());
cmb.getItems().addAll(LISTA);
stage.setScene(new Scene(new StackPane(cmb)));
stage.show();
stage.setTitle("Filtrando um ComboBox");
stage.setWidth(300);
stage.setHeight(300);
new ComboBoxAutoComplete<String>(cmb);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment