Friday, June 3, 2016

22. Menu with Initial state

In the last example, the rectangles were black initially, the default color. Now they will be set Red for left and Green for right.


The colors are put in the constructor for the Rectangle objects. We also use the setSelected() method to select one of the items in the two groups.


package ex22;

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 Ex22 extends Application {
    
    @Override
    public void start(Stage primaryStage) {
        
        Rectangle rectLeft = new Rectangle(100, 200, Color.RED);
        Rectangle rectRight = new Rectangle(100, 200, Color.GREEN);
        
        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);
        red1.setSelected(true);
        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);
        green2.setSelected(true);
        
        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 22. Menu with Initial state");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

This is the output:


No comments:

Post a Comment