0

I have a JavaFx ComboBox containing a long list of items. To find the item I want, when the ComboBox drops down I start typing part of the description and filter for items containing what I type in the descriptions showing in the ComboBox, and the list in the ComboBox shrinks accordingly. That works fine. However, I want to be able to include a spacebar (blank) as part of the search string, but as soon as I press the spacebar, the combobox hides.

I have tried adding an event filter, which does catch the spacebar (and all other keys), but not before the ComboBox hides itself when the spacebar is pressed. Any suggestions on preventing the spacebar from causing the ComboBox to hide would be appreciated. This is the truncated code showing what I have tried.

class MainController
{
    @FXML
    lateinit var cmbPwds: ComboBox<PwdItem>

    init {
        Platform.runLater {setKeyboardEvent()}
    }

    fun setKeyboardEvent() {
        cmbPwds.addEventFilter(KeyEvent.ANY) {event ->
            event.consume()
            if(event.eventType == KeyEvent.KEY_TYPED)
                print(if(event.character == " ") "BLANK" else event.character)
        }
    }
}
Red wine
  • 162
  • 2
  • 11
  • 3
    This is a known bug: [JDK-8209991](https://bugs.openjdk.java.net/browse/JDK-8209991) (and [JDK-8087549](https://bugs.openjdk.java.net/browse/JDK-8087549)). Unfortunately, it doesn't appear any work has been done to fix it. Maybe this other question can help: [How to prevent closing of AutoCompleteCombobox popupmenu on SPACE key press in JavaFX](https://stackoverflow.com/questions/50013972/). – Slaw Sep 15 '19 at 05:47

1 Answers1

0

I don't think this exactly answers your question, but maybe it will help. The code below consumes the space character, leaving the combobox open.

// import javafx.scene.control.skin.ComboBoxListViewSkin;
// ComboBox<T> comboBox;
ComboBoxListViewSkin<T> skin = new ComboBoxListViewSkin<>(comboBox);
skin.getPopupContent().addEventFilter(KeyEvent.ANY, e -> {
    if (e.getCode() == KeyCode.SPACE) {
        e.consume();
    }
});
comboBox.setSkin(skin);
hohonuuli
  • 1,974
  • 15
  • 15
  • why do you duplicate the answer to the other question? Doing so without contribution is called .. plagiate. Probably the only reason the question isn't marked a duplicate is that it's kotlin: so you could add value by translating the other answer into ... kotlin ;) – kleopatra Sep 16 '19 at 16:18
  • My bad. I ran into the same issue a while back and just copied the code straight out of my app as I thought it would be helpful. It's likely I got it from the other issue. Regarding plagarism ... are you suggesting the people might copy and paste code from Stackoverflow?? That's just crazy! ;-) Who would do such a thing?? https://www.goodreads.com/book/show/29437996-copying-and-pasting-from-stack-overflow – hohonuuli Sep 16 '19 at 17:01