单击按钮时如何清除HBox中的ComboBox?

时间:2019-11-27 02:17:32

标签: java javafx

我有一个简单的JavaFX GUI,顶部有一个HBox,其中包含几个ComboBox,这些ComboBox最终将充当过滤器。我无法弄清楚如何在单击“清除”按钮时将ComboBoxes的值重置为空字符串。任何提示将不胜感激。

更新:这是适用于我的代码

      // 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);

1 个答案:

答案 0 :(得分:2)

要清除对组合框的选择,您需要访问SelectionModel。在SelectionModel中,您将找到方法clearSelection(),该方法可在按钮的动作处理程序中使用。假设您熟悉所涉及的其他所有内容,那么您将需要类似以下的内容。

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();
} );