Wednesday, February 8, 2012

JavaFX 2.0: RadioMenuItem and ToggleGroup

JavaFX 2.0: RadioMenuItem and ToggleGroup
package javafx_exmenu;

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

/**
*
* @web http://java-buddy.blogspot.com/
*/
public class JavaFX_exMenu extends Application {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}

@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("java-buddy.blogspot.com");
Group root = new Group();
Scene scene = new Scene(root, 400, 300, Color.WHITE);

//Top Menu Bar
MenuBar menuBar = new MenuBar();

//Radio Menu
Menu radioMenu = new Menu("Radio Menu");

radioMenu.getItems().add(
RadioMenuItemBuilder.create()
.text("Radio Items 1")
.build());
radioMenu.getItems().add(
RadioMenuItemBuilder.create()
.text("Radio Items 2")
.selected(true)
.build());

//Toggle Group Menu
Menu toggleMenu = new Menu("Toggle Menu");
ToggleGroup toggleGroup = new ToggleGroup();
RadioMenuItem radioItemA = new RadioMenuItem("Option A");
RadioMenuItem radioItemB = new RadioMenuItem("Option B");
RadioMenuItem radioItemC = new RadioMenuItem("Option C");
radioItemA.setToggleGroup(toggleGroup);
radioItemB.setToggleGroup(toggleGroup);
radioItemC.setToggleGroup(toggleGroup);
toggleMenu.getItems().add(radioItemA);
toggleMenu.getItems().add(radioItemB);
toggleMenu.getItems().add(radioItemC);

menuBar.getMenus().add(radioMenu); //Add Radio Menu
menuBar.getMenus().add(toggleMenu); //Add Toggle Group Menu

menuBar.prefWidthProperty().bind(primaryStage.widthProperty());
root.getChildren().add(menuBar);
primaryStage.setScene(scene);
primaryStage.show();
}
}

2 comments:

  1. Hello!
    Tnx for such useful and regular posts!

    Which version you use.

    If 2.1.09 and newer, please pay attention, that only "Radio menu" and "Toggle menu" was rendered cool. Subitems have old rendering and that is ugly.

    I filled issue at Jira and used your code ( with your authorship, of course! :) )

    I hope, you will not reject it...

    ReplyDelete
  2. Well, when I try to run this code, there is an error that tell:
    that the principal class can't find it.
    So, or I don't know how I have to run the code...

    ReplyDelete