Java 单击按钮时如何清除HBox中的组合框?

Java 单击按钮时如何清除HBox中的组合框?,java,javafx,Java,Javafx,我有一个简单的javafxgui,上面有一个HBox,它包含几个组合框,最终将充当过滤器。我不知道如何在单击“清除”按钮时将组合框的值重置为空字符串。任何提示都将不胜感激 更新:这是我的代码,适合我 // private EventHandler to pass to the clearButton's action EventHandler<ActionEvent> clearAction = new EventHandler<ActionEvent&

我有一个简单的javafxgui,上面有一个HBox,它包含几个组合框,最终将充当过滤器。我不知道如何在单击“清除”按钮时将组合框的值重置为空字符串。任何提示都将不胜感激

更新:这是我的代码,适合我

      // 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);
//传递给clearButton操作的私有EventHandler
EventHandler clearAction=新的EventHandler(){
@凌驾
公共无效句柄(ActionEvent事件){
List nodes=topPane.getChildren();
用于(节点:节点){
if(组合框的节点实例){
((组合框)节点).getSelectionModel().clearSelection();
}
}
}
};
clearButton.setOnAction(clearAction);

要清除组合框的选择,您需要访问。在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();
} );
ComboBox box=new ComboBox();
box.getItems().addAll(“选项1”、“选项2”、“选项3”);
按钮清除按钮=新按钮(“清除选择”);
clearButton.setOnAction(e->{
box.getSelectionModel().clearSelection();
} );

您看到了吗?谢谢!我使用getSelectionModel().clearSelection()和一个自定义事件处理程序为整个HBox实现了这一点,如下所述: