0

I am making a Editable ComboBox which show any values contain the input and it works fine.

But the problem is in the input field, whenever i typed Space or arrow buttons the input field keep reseting.

I tried setonKeyPressed and setonKeyTyped too but it isn't solve the problem.

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        
        ObservableList<String> fruit = FXCollections.observableArrayList();
        fruit.add("apple");
        fruit.add("orange");
        fruit.add("banana");

        ComboBox myComboBox = new ComboBox();
        myComboBox.setEditable(true);
        myComboBox.setOnKeyReleased(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent keyEvent) {
                myComboBox.getItems().clear();
                myComboBox.show();
                String input = myComboBox.getEditor().getText();
                for ( int i = 0 ; i < fruit.size(); i++) {
                    if(fruit.get(i).contains(input)) {      //Check if the list contains the input
                        myComboBox.getItems().add(fruit.get(i));    
                    }
                }
            }
        });
        
        HBox hbox = new HBox(myComboBox);
        primaryStage.setScene(new Scene(hbox, 300, 275));
        primaryStage.show();
    }
    
    public static void main(String[] args) {
        launch(args);
    }
}
3
  • 1
    minimal reproducible example please.. Commented Oct 3, 2021 at 6:56
  • 1
    @kleopatra i just edited my question again. It was my first time making question here so sorry to watse your time. I will take any advices that make my question better or to solve this problem Commented Oct 3, 2021 at 13:39
  • what do you expect to happen if you explicitly clear the items on any key released ;) Work through a tutorial on how to use keyEvents, and apply what you learned after re-thinking the logic of your handler. Commented Oct 5, 2021 at 15:49

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.