Thursday, June 23, 2016

70. ToolBar

Three buttons, with graphics for red, green, and blue form a ToolBar.


Each graphic is a 40 by 40 png image filled with one color and put in src folder. The text "Red", "Green", or "Blue" is displayed in the label depending on which button is clicked.


package ex70;

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ToolBar;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class Ex70 extends Application {

    private final String style =
            "-fx-font-family: Georgia; -fx-font-size: 32;"
            +"-fx-text-fill: purple;";

    @Override
    public void start(Stage stage) {

        Label label = new Label("Red");
        label.setStyle(style);
        
        ToolBar toolBar = new ToolBar();
        toolBar.setMaxWidth(220);
        toolBar.setPadding(new Insets(20));
        
        Button button1 = new Button();
        Image image1 = new Image("red.png");
        button1.setGraphic(new ImageView(image1));
        button1.setOnAction(e->label.setText("Red"));
        
        Button button2 = new Button();
        Image image2 = new Image("green.png");
        button2.setGraphic(new ImageView(image2));
        button2.setOnAction(e->label.setText("Green"));
        
        Button button3 = new Button();
        Image image3 = new Image("blue.png");
        button3.setGraphic(new ImageView(image3));
        button3.setOnAction(e->label.setText("Blue"));
        
        toolBar.getItems().addAll(button1, button2, button3);
        
        VBox vbox = new VBox(20, toolBar, label);
        vbox.setAlignment(Pos.CENTER);
        vbox.setPadding(new Insets(30));
        vbox.setStyle("-fx-background-color: lime");

        Scene scene = new Scene(vbox, 400, 300);
        stage.setTitle("Example 70. ToolBar");

        stage.setScene(scene);
        stage.show();
    }
    
    public static void main(String[] args) {
        launch();
    }
}

This is the output:


No comments:

Post a Comment