0

I read AutoComplete ComboBox in JavaFX but the answer with the most upvotes uses Lambda expressions.

In my project i can't use them, so I would like to ask if someone could provide the code without lambda expressions.

Here are the two parts of the code with lambda expressions:

1)

comboBox.getEditor().focusedProperty().addListener(observable -> {
            if (comboBox.getSelectionModel().getSelectedIndex() < 0) {
                comboBox.getEditor().setText(null);
            }
        });

2)

comboBox.addEventHandler(KeyEvent.KEY_PRESSED, t -> comboBox.hide());
Community
  • 1
  • 1
Felix S
  • 25
  • 1
  • 3
  • 2
    Every lambda expression can be converted to a anonymus class. However not being allowed to use lambdas in javafx **8** seems to be a absurd constraint since there are classes in the API using lambdas... – fabian Mar 24 '17 at 17:16
  • I use version 7. Just wanted to tagg it under javafx-8 so people who know lamda expressions see this. – Felix S Mar 24 '17 at 17:56
  • You should be able to determine how to write non-lambda implementations by looking at the documentation for the two methods: [Observable.addListener](http://docs.oracle.com/javase/8/javafx/api/javafx/beans/Observable.html#addListener-javafx.beans.InvalidationListener-) and [Node.addEventHandler](http://docs.oracle.com/javase/8/javafx/api/javafx/scene/Node.html#addEventHandler-javafx.event.EventType-javafx.event.EventHandler-). Assuming you are familiar with writing anonymous classes, that is. – VGR Mar 24 '17 at 19:13

2 Answers2

4

If you're willing to use external libraries, you can make an autocompleting ComboBox with just a few lines of code using ControlsFX.

ComboBox<String> comboBox = new ComboBox<>();
comboBox.getItems().addAll("Hello", "Hello World", "Hey");
comboBox.setEditable(true);
TextFields.bindAutoCompletion(comboBox.getEditor(), comboBox.getItems());

controlsFX autocomplete box

Stevoisiak
  • 23,794
  • 27
  • 122
  • 225
1

Your IDE should be able to convert back and forth. Below is a sample of using that in Eclipse.

1)

comboBox.getEditor().focusedProperty().addListener(new InvalidationListener() {
            @Override
            public void invalidated(Observable observable) {
                 if (comboBox.getSelectionModel().getSelectedIndex() < 0) {
                     comboBox.getEditor().setText(null);
                 }
            }
        });

2)

comboBox.addEventHandler(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent t) {
                comboBox.hide();
            }
        });

Hope that helps.

purring pigeon
  • 4,141
  • 5
  • 35
  • 68