JavFX 2 MenuButton

I’m trying to create a MenuButton with multiple items. Then, when one of the items is clicked, grab it’s value. But can’t figure out how to do this?

Here is a snippet from my FXML:

<MenuButton fx:id="changeStatusButton" layoutX="420.0" layoutY="16.0" mnemonicParsing="false" onAction="#changeStatusFired" prefHeight="26.0" prefWidth="180.0" text="Change My Status" AnchorPane.rightAnchor="17.0">
  <items>
    <MenuItem mnemonicParsing="false" text="Set Available" />
    <MenuItem mnemonicParsing="false" text="Set Unavailable" />
  </items>
</MenuButton>

How would I go about grabbing the text from the selected item? So if the first item is selected, I would like to get the text “Set Available” to perform an action based on that. But can’t figure out how to do that? For a textfield this is easy, but have no idea how these MenuButtons work. All the information I’ve found only tells you how to populate them, but I’ve already pre-populated them…

Answer

Menus and MenuButtons don’t maintain a “selectedItem” state. The MenuItems fire ActionEvents when the user clicks on them (or invokes their action via a keyboard shortcut). So you need to register action listeners for them:

<MenuButton fx:id="changeStatusButton" layoutX="420.0" layoutY="16.0" mnemonicParsing="false" prefHeight="26.0" prefWidth="180.0" text="Change My Status" AnchorPane.rightAnchor="17.0">
  <items>
    <MenuItem mnemonicParsing="false" onAction="#setAvailable" text="Set Available" />
    <MenuItem mnemonicParsing="false" onAction="#setUnavailable" text="Set Unavailable" />
  </items>
</MenuButton>

and then in your controller:

private boolean available ;

// ...

@FXML
private void setAvailable(ActionEvent event) {
    available = true ;
}

@FXML
private void setUnavailable(ActionEvent event) {
    available = false ;
}

If you want true selection functionality, you should consider using a ComboBox. Obviously in this example a CheckBox would be the best option, but I assume your real example has more choices.

Leave a Reply

Your email address will not be published. Required fields are marked *