首先是 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());
});
}
输出:
编辑:
以下是获取索引的方法:
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/