Wednesday, June 22, 2016

65. RadioButton

A set of 3 RadioButtons, part of a ToggleGroup, can select between triangle, square or pentagon shape.


The visibility of the shape node is dependent on the state of button's selectedProperty through a unidirectional bind. For the Polygon shapes, we construct the double array using getDouble method which requires the number of sides (which is also equal to the number of vertices of points in our array).


package ex65;

import javafx.application.Application;
import javafx.geometry.Point2D;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.paint.Color;
import javafx.scene.shape.Polygon;
import javafx.stage.Stage;

public class Ex65 extends Application {

    final int RADIUS = 100;
    final Point2D CENTER = new Point2D(200, 200);
    
    @Override
    public void start(Stage stage) {
                        
        Group root = new Group();
        
        RadioButton triangleButton = new RadioButton("Triangle");
        triangleButton.setLayoutX(10); triangleButton.setLayoutY(10);
        RadioButton squareButton = new RadioButton("Square");
        squareButton.setLayoutX(10); squareButton.setLayoutY(60);
        RadioButton pentagonButton = new RadioButton("Pentagon");
        pentagonButton.setLayoutX(10); pentagonButton.setLayoutY(110);
        
        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(
                triangleButton.selectedProperty());
        square.visibleProperty().bind(
                squareButton.selectedProperty());
        pentagon.visibleProperty().bind(
                pentagonButton.selectedProperty());
        
        root.getChildren().addAll(triangleButton,
                squareButton, pentagonButton,
                triangle, square, pentagon);
        
        ToggleGroup toggleGroup = new ToggleGroup();
        toggleGroup.getToggles().addAll(triangleButton,
                squareButton, pentagonButton);
        
        Scene scene = new Scene(root, 400, 400, Color.CORNSILK);
        stage.setTitle("Example 65. RadioButton");
        
        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)+CENTER.getX();
            array[2*i+1]=RADIUS*Math.sin(2*Math.PI/n*i)+CENTER.getY();
        }
        return array;
    }
    
    public static void main(String[] args) {
        launch();
    }
}

This is the output when the pentagon button is selected:


No comments:

Post a Comment