Pular para o conteúdo principal

Simplest JavaFX ComboBox autocomplete

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

  • 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.


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);
}
}

Comentários

  1. Little bugfix (in your simple example tootlip position it's OK, but in other complex cases it isn`t):

    double posX = stage.getX() + comboBox.localToScene(comboBox.getBoundsInLocal()).getMinX();
    double posY = stage.getY() + comboBox.localToScene(comboBox.getBoundsInLocal()).getMinY();

    It runs very good! Congrats :)

    ResponderExcluir
  2. My solution, which fixes some bugs:

    import 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);
    }

    }

    ResponderExcluir

Postar um comentário

Postagens mais visitadas deste blog

Dancing lights with Arduino - The idea

I have been having fun with Arduino these days! In this article I am going to show how did I use an electret mic with Arduino to create a Dancing Lights circuit. Dancing Lights   I used to be an eletronician before starting the IT college. I had my own electronics maintenance office to fix television, radios, etc. In my free time I used to create electronic projects to sell and I made a few "reais" selling a version of Dancing lights, but it was too limited: it simply animated lamps using a relay in the output of a 4017 CMOS IC. The circuit was a decimal counter  controlled by a 555. 4017 decimal counter. Source in the image When I met Arduino a few years ago, I was skeptical because I said: I can do this with IC, why should I use a microcontroller. I thought that Arduino was for kids. But now my pride is gone and I am having a lot of fun with Arduino :-) The implementation of Dancing Lights with Arduino uses an electret mic to capture the sound and light leds...

Creating Fat JARs for JavaFX Applications

A FAT JAR is a type of Java application distribution where a single JAR contains all other dependencies, so no additional file is required to run the JAR besides the Java Virtual Machine. For any Java maven based application, creating a FAR JAR could be solved by using Maven Shade Plugin . However, creating FAT Jars using JavaFX may be a challenge because JavaFX uses modules. Fortunately this subject was intensely discussed in the WEB, and a good explanation and a solution was provided by Jose Pereda in this StackOverflow response. In this post I want to briefly share the steps to make a FAT JAR and post an example on my github so I can point others to check the example. How to create a FAT JAR for a JavaFX application? 1- Create a main class that will run your application. This class must have the main method and call your actual application static launch method; 2- Add the Shade Plugin to your project. For those using Gradle notice that Jose Pereda also provided an answer about it i...