Thursday, June 2, 2016

21. Menu

A BorderPane layout is used with 3 nodes set. The top is menuBar (a MenuBar object), the left is a rectLeft, and right is rectRight (both Rectangle objects).


Depending on the selection of Left or Right, the rectangle is changed in Color, and we get a visual check as shown in the Output Figure below.


package ex21;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.RadioMenuItem;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.BorderPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

public class Ex21 extends Application {
    
    @Override
    public void start(Stage primaryStage) {
        
        Rectangle rectLeft = new Rectangle(100, 200);
        Rectangle rectRight = new Rectangle(100, 200);
        
        BorderPane root = new BorderPane();
        
        MenuBar menuBar = new MenuBar();
        Menu leftMenu = new Menu("Left");
        ToggleGroup leftColor = new ToggleGroup();
        RadioMenuItem red1 = new RadioMenuItem("Red");
        RadioMenuItem green1 = new RadioMenuItem("Green");
        RadioMenuItem blue1 = new RadioMenuItem("Blue");
        red1.setToggleGroup(leftColor);
        green1.setToggleGroup(leftColor);
        blue1.setToggleGroup(leftColor);
        Menu rightMenu = new Menu("Right");
        ToggleGroup rightColor = new ToggleGroup();
        RadioMenuItem red2 = new RadioMenuItem("Red");
        RadioMenuItem green2 = new RadioMenuItem("Green");
        RadioMenuItem blue2 = new RadioMenuItem("Blue");
        red2.setToggleGroup(rightColor);
        green2.setToggleGroup(rightColor);
        blue2.setToggleGroup(rightColor);
        
        red1.setOnAction(e -> rectLeft.setFill(Color.RED));
        green1.setOnAction(e -> rectLeft.setFill(Color.GREEN));
        blue1.setOnAction(e -> rectLeft.setFill(Color.BLUE));
        red2.setOnAction(e -> rectRight.setFill(Color.RED));
        green2.setOnAction(e -> rectRight.setFill(Color.GREEN));
        blue2.setOnAction(e -> rectRight.setFill(Color.BLUE));
 
        leftMenu.getItems().addAll(red1, green1, blue1);
        rightMenu.getItems().addAll(red2, green2, blue2);
        menuBar.getMenus().addAll(leftMenu, rightMenu);
    
        root.setTop(menuBar);
        root.setRight(rectRight);
        root.setLeft(rectLeft);
        
        Scene scene = new Scene(root, 400, 400);
        
        primaryStage.setTitle("Example 21. Menu");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

This is the output:


No comments:

Post a Comment