开发者社区> 问答> 正文

Hbox有子Buttons,如何获取和添加监听器?

首先是FXML,它是一个内部带有Button的简单Hbox:

 <HBox fx:id="hboxOfCategories" alignment="CENTER_LEFT" spacing="10.0">
           <children>
              <Button maxHeight="1.7976931348623157E308" mnemonicParsing="false" prefHeight="57.0" prefWidth="82.0" text="Boissons" />
              <Button layoutX="10.0" layoutY="10.0" maxHeight="1.7976931348623157E308" mnemonicParsing="false" prefHeight="57.0" prefWidth="82.0" text="Burger" />
              <Button layoutX="102.0" layoutY="10.0" maxHeight="1.7976931348623157E308" mnemonicParsing="false" prefHeight="57.0" prefWidth="82.0" text="Tacos" />
              <Button layoutX="378.0" layoutY="10.0" maxHeight="1.7976931348623157E308" mnemonicParsing="false" prefHeight="57.0" prefWidth="82.0" text="Pizza" />
              <Button layoutX="194.0" layoutY="10.0" maxHeight="1.7976931348623157E308" mnemonicParsing="false" prefHeight="57.0" prefWidth="82.0" text="Baguette Farcie" textAlignment="CENTER" wrapText="true" />
              <Button layoutX="286.0" layoutY="10.0" maxHeight="1.7976931348623157E308" mnemonicParsing="false" prefHeight="57.0" prefWidth="82.0" text="Souflee" />
           </children>
        </HBox>

我将他的内容保存在Observable列表中,它必须是Node类型,因为.getChildren()方法返回的是Node类型:

fxml控制器代码:

@FXML
    private void initialize(){

    ObservableList<Node> hboxButtons = hboxOfCategories.getChildren();

}

我如何抓住这些按钮并向它们添加一个监听器,这些监听器在单击按钮时触发?像这样的东西:

hboxofCategories.getchildren().addlistener(e -> {
doEpicStuff();
});

问题来源:Stack Overflow

展开
收起
montos 2020-03-25 21:42:35 707 0
1 条回答
写回答
取消 提交回答
  • 这应该可以解决问题:

    for(Node button : hboxOfCategories.getChildren())
        {
            ((Button)button).setOnAction(a -> {
                    System.out.println("Pressed : "+ ((Button)button).getText());
                });
        }
    

    编辑:

    这是获取索引的方法:

    for(int i=0;i<hboxOfCategories.getChildren().size();i++)
    {
        Button button=(Button)hboxOfCategories.getChildren().get(i);
        int index=i;
        button.setOnAction(a->
                           {
                               System.out.println("Name : "+button.getText()+" | Index : "+index);
                           });
    }
    

    回答来源:Stack Overflow

    2020-03-25 21:43:25
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载