Class RadioMenuItem

  • All Implemented Interfaces:
    Styleable, EventTarget, Toggle


    public class RadioMenuItem
    extends MenuItem
    implements Toggle

    A RadioMenuItem is a MenuItem that can be toggled (it uses the Toggle mixin). This means that RadioMenuItem has an API very similar in nature to other controls that use Toggle, such as RadioButton and ToggleButton. RadioMenuItem is specifically designed for use within a Menu, so refer to that class API documentation for more information on how to add a RadioMenuItem into it.

    To create a simple, ungrouped RadioMenuItem, do the following:

    
    RadioMenuItem radioItem = new RadioMenuItem("radio text");
    radioItem.setSelected(false);
    radioItem.setOnAction(new EventHandler<ActionEvent>() {
        @Override public void handle(ActionEvent e) {
            System.out.println("radio toggled");
        }
    });
    

    The problem with the example above is that this offers no benefit over using a normal MenuItem. As already mentioned, the purpose of a RadioMenuItem is to offer multiple choices to the user, and only allow for one of these choices to be selected at any one time (i.e. the selection should be mutually exclusive). To achieve this, you can place zero or more RadioMenuItem's into groups. When in groups, only one RadioMenuItem at a time within that group can be selected. To put two RadioMenuItem instances into the same group, simply assign them both the same value for toggleGroup. For example:

    
    ToggleGroup toggleGroup = new ToggleGroup();
    
    RadioMenuItem radioItem1 = new RadioMenuItem("Option 1");
    radioItem.setOnAction(new EventHandler<ActionEvent>() {
        @Override public void handle(ActionEvent e) {
            System.out.println("radio toggled");
        }
    });
    radioItem1.setToggleGroup(toggleGroup);
    RadioMenuItem radioItem2 = new RadioMenuItem("Option 2");
    radioItem.setOnAction(new EventHandler<ActionEvent>() {
        @Override public void handle(ActionEvent e) {
            System.out.println("radio toggled");
        }
    });
    radioItem2.setToggleGroup(toggleGroup);
    
    
    In this example, with both RadioMenuItem's assigned to the same ToggleGroup, only one item may be selected at any one time, and should the selection change, the ToggleGroup will take care of deselecting the previous item.
    Since:
    JavaFX 2.0
    See Also:
    MenuItem, Menu