-1

I have a simple JavaFX GUI where I have an HBox across the top that contains several ComboBoxes that will eventually act as filters. I can't figure out how to reset the value of the ComboBoxes to an empty string when clicking a "clear" button. Any tips would be appreciated.

Update: Here's my code that works for me

      // private EventHandler to pass to the clearButton's action
      EventHandler<ActionEvent> clearAction = new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent event) {

          List<Node> nodes = topPane.getChildren();

          for (Node node : nodes) {
            if (node instanceof ComboBox) {
              ((ComboBox) node).getSelectionModel().clearSelection();
            }
          }
        }

      };


      clearButton.setOnAction(clearAction);
  • Have you seen [Combobox clearing value issue](https://stackoverflow.com/questions/12142518/combobox-clearing-value-issue) ? – Abra Nov 27 '19 at 02:44

1 Answers1

2

To clear the selection of a ComboBox, you need to access the SelectionModel. In the SelectionModel you'll find a method clearSelection() which can be used in the action handler for button. Assuming you're familiar with everything else involved, you'll want something like the following.

ComboBox<String> box = new ComboBox<>();
box.getItems().addAll( "Choice 1", "Choice 2", "Choice 3" );

Button clearButton = new Button( "Clear Selection" );
clearButton.setOnAction( e -> {
    box.getSelectionModel().clearSelection();
} );
  • Thanks! I managed to do this for the entire HBox using your getSelectionModel().clearSelection() and a making a custom EventHandler as mentioned here: https://stackoverflow.com/a/44138558/10752516 – myshortfriend Nov 27 '19 at 03:03