JavaFX TextField Auto-suggestions

后端 未结 5 740
我寻月下人不归
我寻月下人不归 2020-11-29 07:12

I want to make this TextField have suggestions feature just like in Lucene. I\'ve searched all the web and I just find it for ComboBox.

TextField instNameTxt         


        
5条回答
  •  天涯浪人
    2020-11-29 07:24

    There is another solution with JFoenix. Since February 2018 they added autocompletion class. This is implementation of it.

    // when initializing the window or in some other method
    void initialize() {
        JFXAutoCompletePopup autoCompletePopup = new JFXAutoCompletePopup<>();
        autoCompletePopup.getSuggestions().addAll("option1", "option2", "...");
    
        autoCompletePopup.setSelectionHandler(event -> {
            textField.setText(event.getObject());
    
            // you can do other actions here when text completed
        });
    
        // filtering options
        textField.textProperty().addListener(observable -> {
            autoCompletePopup.filter(string -> string.toLowerCase().contains(textField.getText().toLowerCase()));
            if (autoCompletePopup.getFilteredSuggestions().isEmpty() || textField.getText().isEmpty()) {
                autoCompletePopup.hide();
                // if you remove textField.getText.isEmpty() when text field is empty it suggests all options
                // so you can choose
            } else {
                autoCompletePopup.show(textField);
            }
        });
    }
    

    This is a bit new approach and worked fine with me. Hope it will help and thanks to JFoenix developers.

提交回复
热议问题