Based on this Brazilian community post, I've created a sample Combobox auto complete. What it basically does is:

The class code and a sample application is below. I also added the source to my personal github, sent me PR to improve it and there are a lot of things to improve, like space and accents support.
- When user type with the combobox selected, it will work on a temporary string to store the typed text;
- Each key typed leads to the combobox to be showed and updated
- If backspace is type, we update the filter
- Each key typed shows the combo box items, when the combobox is hidden, the filter is cleaned and the tooltip is hidden:

The class code and a sample application is below. I also added the source to my personal github, sent me PR to improve it and there are a lot of things to improve, like space and accents support.
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 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); | |
} | |
} |
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.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); | |
} | |
} |
Little bugfix (in your simple example tootlip position it's OK, but in other complex cases it isn`t):
ResponderExcluirdouble posX = stage.getX() + comboBox.localToScene(comboBox.getBoundsInLocal()).getMinX();
double posY = stage.getY() + comboBox.localToScene(comboBox.getBoundsInLocal()).getMinY();
It runs very good! Congrats :)
My solution, which fixes some bugs:
ResponderExcluirimport java.util.List;
import java.util.stream.Collectors;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
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;
import org.apache.commons.lang3.StringUtils;
public class ComboBoxAutoComplete extends ComboBox {
private ObservableList originalItems;
private StringProperty filter = new SimpleStringProperty(StringUtils.EMPTY);
private AutoCompleteComparator comparator = (typedText, objectToCompare) -> false;
public interface AutoCompleteComparator {
boolean matches(String typedText, T objectToCompare);
}
public void initialize(AutoCompleteComparator comparator) {
this.comparator = comparator;
this.originalItems = FXCollections.observableArrayList(getItems());
setTooltip(new Tooltip());
getTooltip().textProperty().bind(filter);
filter.addListener((observable, oldValue, newValue) -> handleFilterChanged(newValue));
setOnKeyPressed(this::handleOnKeyPressed);
setOnHidden(this::handleOnHiding);
}
private void handleOnKeyPressed(KeyEvent keyEvent) {
KeyCode code = keyEvent.getCode();
String filterValue = filter.get();
if (code.isLetterKey()) {
filterValue += keyEvent.getText();
} else if (code == KeyCode.BACK_SPACE && filterValue.length() > 0) {
filterValue = filterValue.substring(0, filterValue.length() - 1);
} else if (code == KeyCode.ESCAPE) {
filterValue = StringUtils.EMPTY;
} else if (code == KeyCode.DOWN || code == KeyCode.UP) {
show();
}
filter.setValue(filterValue);
}
private void handleFilterChanged(String newValue) {
if (StringUtils.isNoneBlank(newValue)) {
show();
if (StringUtils.isBlank(filter.get())) {
restoreOriginalItems();
} else {
showTooltip();
getItems().setAll(filterItems());
}
} else {
getTooltip().hide();
}
}
private void showTooltip() {
if (!getTooltip().isShowing()) {
Window stage = getScene().getWindow();
double posX = stage.getX() + localToScene(getBoundsInLocal()).getMinX() + 4;
double posY = stage.getY() + localToScene(getBoundsInLocal()).getMinY() - 29;
getTooltip().show(stage, posX, posY);
}
}
private ObservableList filterItems() {
List filteredList = originalItems.stream().filter(el -> comparator.matches(filter.get().toLowerCase(), el)).collect(Collectors.toList());
return FXCollections.observableArrayList(filteredList);
}
private void handleOnHiding(Event e) {
filter.setValue(StringUtils.EMPTY);
getTooltip().hide();
restoreOriginalItems();
}
private void restoreOriginalItems() {
T s = getSelectionModel().getSelectedItem();
getItems().setAll(originalItems);
getSelectionModel().select(s);
}
}