Kamper K :
to start here's the FXML, a simple Hbox with Buttons inside :
<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>
i saved his content inside an Observable list , it had to be type Node because the .getChildren() method returns something that's type Node :
fxml controller code :
@FXML
private void initialize(){
ObservableList<Node> hboxButtons = hboxOfCategories.getChildren();
}
How can i grab those buttons and add a listener to them that triggers when the buttons are clicked ? something like this :
hboxofCategories.getchildren().addlistener(e -> {
doEpicStuff();
});
adxl :
This should do the trick :
for(Node button : hboxOfCategories.getChildren())
{
((Button)button).setOnAction(a -> {
System.out.println("Pressed : "+ ((Button)button).getText());
});
}
Output :
EDIT :
Here is how you can get the index :
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);
});
}
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=277044&siteId=1