1

I just started transitioning from Swing to JavaFX (forever) and i've gotten pretty good so far! I have managed to populate a ComboBox from a list of entities and adding a blank item on top of the list, like such :

supplierSearch = new ComboBox();
    ObservableList<Supplier> suppliers = FXCollections.observableArrayList(supplierService.findAll());
    suppliers.add(0, new Supplier());
    supplierSearch.setItems(suppliers);
    supplierSearch.setPromptText("Recherche Fournisseur");
    supplierSearch.setMaxWidth(Double.MAX_VALUE);
    supplierSearch.getSelectionModel().selectedItemProperty().addListener((observable) -> 
    {
        filterProducts();
    });

One thing that bothers me is that the prompt text never comes back when selecting the blank item, it is only there when the ComboBox is initially created and as soon as you click an item (or the blank line in the first position) it never reappears. Is there a way to show the prompt text back when selecting the blank item?

Thanks!

Martin
  • 1,977
  • 5
  • 30
  • 67
  • 2
    `supplierSearch.getSelectionModel().clearSelection()`. You may need to use `Platform.runLater` though to avoid modifying the selected item from a listener to that property. – fabian Sep 03 '18 at 18:30
  • empty items are always a bad idea .. – kleopatra Sep 04 '18 at 07:30

2 Answers2

1

I know I'm late, but someone could read this looking for information.

It's important to say that while it works, its not the best solution. I don't know what type your ComboBox is set to, but I assume you're using it with String, so you can set the first item to the text you want.

The problem here is that if you select this combobox item youll be returning this exact String with getSelecionModel().getSelectedItem()

But which is worse, if you set your ComboBox to be populated with your own object, you wont be able to bind the ComboBox value to your model using getSelecionModel().selectedItemProperty() and you'll have an error there.

As someone said up in the comments, use the getSelecionModel().ClearSelection().

-1

Well, i kinda hacked this. I just set the blank entity's name to be the same thing as the prompt text. Since a ComboBox's prompt text displays in the same exact way as the actual text of the selected item, this works nicely.

Martin
  • 1,977
  • 5
  • 30
  • 67
  • why hacking when you could solve it cleanly (see fabians comment) – kleopatra Sep 04 '18 at 07:28
  • Platform.runLater(() -> { comboBox.getSelectionModel().clearSelection(); }); doesn't work for me using JavaFX 19. I would be interested if anybody knows how to do this with a current version – Alex Oct 30 '22 at 09:58