Tuesday, May 24, 2016

1. Four Buttons in a Grid

A GridPane layout is used to organize 4 buttons in a 2 by 2 grid structure.


All four buttons route to select(int) function but pass in a different int, which is the output of the console.


package ex01;

import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;

public class Ex01 extends Application {
    
    Stage window;

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

    @Override
    public void start(Stage primaryStage) throws Exception {
        window = primaryStage;
        window.setTitle("Example 1. Four Buttons in a Grid");
                
        GridPane grid = new GridPane();
        grid.setVgap(100);
        grid.setHgap(100);
        grid.setAlignment(Pos.CENTER);
        
        Button button1 = new Button("Button 1");
        GridPane.setConstraints(button1, 0, 0);
        button1.setOnAction(e -> select(1));
        
        Button button2 = new Button("Button 2");
        GridPane.setConstraints(button2, 1, 0);
        button2.setOnAction(e -> select(2));
        
        Button button3 = new Button("Button 3");
        GridPane.setConstraints(button3, 0, 1);
        button3.setOnAction(e -> select(3));
        
        Button button4 = new Button("Button 4");
        GridPane.setConstraints(button4, 1, 1);
        button4.setOnAction(e -> select(4));
        
        grid.getChildren().addAll(button1, button2, button3, button4);

        Scene scene = new Scene(grid, 640, 480);
        window.setScene(scene);
        window.show();
    }

    private void select(int i) {
        System.out.println("The button selected is " + i);
    }
}

This is the output:


No comments:

Post a Comment