How To Get Selected Item From Menu Button javaFX?

11,809

Solution 1


As i can 👀:

A MenuButton control looks like a button and behaves like a menu. When it is activated (by clicking or other means), it shows a list of options in the form of a pop-up menu. The list of options in the menu is maintained in an ObservableList whose reference is returned by the getItems() method. To execute a command when a menu option is selected, you need to add the ActionEvent handler to the MenuItems.

So it has not build in mechanism for detecting which MenuItem is selected...

Except if you are using RadioMenuItemor CheckMenuItemwith groups,that is other story..In that case you can get the selected item from the ToggleGroup you are using to group those buttons.


Solution:

For each MenuItem you have added into the MenuButton ObservableList add an actionListener:

 while (it.hasNext()){
     MenuItem item = new MenuItem(it.next());
     item.setOnAction(a->{ //lambda expression
        //..code logic here for each extension
     });
     format.getItems().add(item);
 }

Solution 2

I found this solution by doing a Google search.

Override
public void start(Stage stage) {
    Group root = new Group();
    Scene scene = new Scene(root);
    stage.setScene(scene);


    ChoiceBox<String> cb = new ChoiceBox(FXCollections.observableArrayList("item1", "item2", "item3"));
    cb.getSelectionModel().selectedIndexProperty().addListener((ObservableValue<? extends Number> observable, Number oldValue, Number newValue) -> {
        String selectedItem = cb.getValue();
        Alert alert = new Alert(AlertType.INFORMATION);
        alert.setTitle("Example");
        alert.setContentText("You clicked " + cb.getItems().get((Integer)newValue));
        alert.showAndWait();
    });


    root.getChildren().add(cb);
    stage.show();
}

You can play around with this until you get your desired results.

Share:
11,809
thvardhan
Author by

thvardhan

Updated on June 05, 2022

Comments

  • thvardhan
    thvardhan about 2 years

    i have just started javaFX and i have made a ButtonMenu with few options. i want to get what user selects from menu.

    here is my code so far ->

    controller class >

    @FXML
    private JFXTextField locF;
    private File file;
    private Set<String> extensions;
    @FXML
    private MenuButton format;
    
    
    public void openFileBrowser(ActionEvent event){
    
    
        DirectoryChooser chooser = new DirectoryChooser();
        chooser.setTitle("JavaFX Projects");
        chooser.setInitialDirectory(new File("c:/"));
        File selectedDirectory = chooser.showDialog(Main.stage);
        locF.setText(selectedDirectory+"");
        extensions=getFileTypes(selectedDirectory.listFiles());//just gets all different types format present in the folder and later add it to menu
        Iterator<String> it=extensions.iterator();
        while (it.hasNext()){
         format.getItems().addAll(new MenuItem(it.next()));
        }
    }
    
    private Set<String> getFileTypes(File[] list){
        Set<String> ext=new HashSet<>();
        for (File i:
             list) {
    
            if (i.isFile()){
    
    
                    ext.add(i.getName().substring(i.getName().lastIndexOf(".")));
    
    
    
            }
    
        }
    
        return ext;
    }
    

    }

    FXML ->

    <?xml version="1.0" encoding="UTF-8"?>
    
    <?import com.jfoenix.controls.JFXButton?>
    <?import com.jfoenix.controls.JFXTextField?>
    <?import javafx.scene.control.Label?>
    <?import javafx.scene.control.MenuButton?>
    <?import javafx.scene.control.MenuItem?>
    <?import javafx.scene.layout.BorderPane?>
    <?import javafx.scene.layout.ColumnConstraints?>
    <?import javafx.scene.layout.GridPane?>
    <?import javafx.scene.layout.RowConstraints?>
    
    <BorderPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.102" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Controller">
       <top>
          <GridPane BorderPane.alignment="CENTER">
            <columnConstraints>
                <ColumnConstraints hgrow="SOMETIMES" maxWidth="295.0" minWidth="10.0" prefWidth="57.0" />
                <ColumnConstraints hgrow="SOMETIMES" maxWidth="295.0" minWidth="10.0" prefWidth="93.0" />
              <ColumnConstraints hgrow="SOMETIMES" maxWidth="564.0" minWidth="10.0" prefWidth="311.0" />
              <ColumnConstraints hgrow="SOMETIMES" maxWidth="575.0" minWidth="0.0" prefWidth="77.0" />
                <ColumnConstraints hgrow="SOMETIMES" maxWidth="575.0" minWidth="10.0" prefWidth="69.0" />
            </columnConstraints>
            <rowConstraints>
              <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
              <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
              <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
            </rowConstraints>
             <children>
                <JFXTextField fx:id="locF" focusColor="#47c64d" unFocusColor="#821dda" GridPane.columnIndex="2" GridPane.rowIndex="1" />
                <JFXButton fx:id="browse" mnemonicParsing="false" onAction="#openFileBrowser" prefHeight="78.0" prefWidth="123.0" ripplerFill="#2de823" text="Browse" GridPane.columnIndex="3" GridPane.rowIndex="1" />
                <Label fx:id="locL" prefHeight="48.0" prefWidth="143.0" text="Enter Location" GridPane.columnIndex="1" GridPane.rowIndex="1" />
             </children>
          </GridPane>
       </top>
       <right>
          <GridPane BorderPane.alignment="CENTER">
            <columnConstraints>
              <ColumnConstraints hgrow="SOMETIMES" maxWidth="95.0" minWidth="10.0" prefWidth="61.0" />
              <ColumnConstraints hgrow="SOMETIMES" maxWidth="139.0" minWidth="10.0" prefWidth="139.0" />
            </columnConstraints>
            <rowConstraints>
              <RowConstraints maxHeight="98.0" minHeight="0.0" prefHeight="17.0" vgrow="SOMETIMES" />
              <RowConstraints maxHeight="227.0" minHeight="10.0" prefHeight="227.0" vgrow="SOMETIMES" />
              <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
            </rowConstraints>
             <children>
                <MenuButton fx:id="format" mnemonicParsing="false" prefHeight="29.0" prefWidth="109.0" text="Format" GridPane.columnIndex="1">
    
                </MenuButton>
             </children>
          </GridPane>
       </right>
    </BorderPane>

    i have tried going to oracle but haven't found any info. Any help is appreciated.