java - Hbox 有子 Buttons ,如何抓取它们并为其添加监听器?

标签 java javafx observablelist

首先是 FXML,一个内部带有按钮的简单 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 Controller 代码:

@FXML
    private void initialize(){

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

}

我怎样才能捕获这些按钮并向它们添加一个监听器,在单击按钮时触发? 像这样的东西:

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

最佳答案

这应该可以解决问题:

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

输出:

enter image description here

编辑:

以下是获取索引的方法:

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

关于java - Hbox 有子 Buttons ,如何抓取它们并为其添加监听器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60686171/

相关文章:

当 DataInputStream 处于 while 循环中时 JavaFX GUI 卡住

java - 更新 observableList 的更有效方法

java - Draw2D/GEF : How to access nested figures (e. g.,用于连接)

Java - 排名/匹配句子

java - 单例模式推荐方法

java - 是否可以在 JavaFX 中将 ImageView 放在 Canvas 上?

java - 通过 TableView 更新值时出现 ClassCast 异常

java - ObservableList 不更新 ArrayList

java - 如何通过操作 ObservableList 来引发置换事件?

java - 使用箭头键绘制线条并在重绘中添加每条新线条