Thursday, June 23, 2016

66. CheckBox

Like the previous example, we can select triangle, square or pentagon, by selecting the appropriate CheckBox.


Now we can select more than one choice.


package ex66;

import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Polygon;
import javafx.stage.Stage;

public class Ex66 extends Application {

    final int RADIUS = 100;
    
    @Override
    public void start(Stage stage) {
                        
        VBox root = new VBox(20);
        root.setAlignment(Pos.CENTER);
        
        HBox hbox = new HBox(50);
        hbox.setAlignment(Pos.CENTER);
        
        CheckBox triangleCB = new CheckBox("Triangle");
        CheckBox squareCB = new CheckBox("Square  ");
        CheckBox pentagonCB = new CheckBox("Pentagon ");
        hbox.getChildren().setAll(triangleCB, squareCB,
                pentagonCB);
        
        Polygon triangle = new Polygon(getDouble(3));
        triangle.setFill(Color.RED);
        
        Polygon square = new Polygon(getDouble(4));
        square.setFill(Color.BLUE);
        
        Polygon pentagon = new Polygon(getDouble(5));
        pentagon.setFill(Color.GREEN);
        
        triangle.visibleProperty().bind(
                triangleCB.selectedProperty());
        square.visibleProperty().bind(
                squareCB.selectedProperty());
        pentagon.visibleProperty().bind(
                pentagonCB.selectedProperty());
        
        root.getChildren().addAll(hbox,
                triangle, square, pentagon);
        
        Scene scene = new Scene(root, 400, 800, Color.CORNSILK);
        stage.setTitle("Example 66. CheckBox");
        
        stage.setScene(scene);
        stage.show();
    }
    
    private double[] getDouble (int n) {
        double[] array = new double[2*n];
        for (int i = 0; i<n; i++){
            array[2*i] = RADIUS*Math.cos(2*Math.PI/n*i);
            array[2*i+1]=RADIUS*Math.sin(2*Math.PI/n*i);
        }
        return array;
    }
    
    public static void main(String[] args) {
        launch();
    }
}

This is the output after selecting triangle and pentagon:


No comments:

Post a Comment