Saturday, September 13, 2014

JavaFX TilePane example


package javafxtilepane;

import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Orientation;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.TilePane;
import javafx.stage.Stage;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFXTilePane extends Application {
    
    @Override
    public void start(Stage primaryStage) {
        
        TilePane tilePane = new TilePane();
        tilePane.setPrefColumns(3);
        tilePane.setPadding(new Insets(5, 5, 5, 5));
        tilePane.setVgap(5);
        tilePane.setHgap(5);
        tilePane.setStyle("-fx-background-color: D0D0D0;");
        tilePane.setAlignment(Pos.CENTER);
        
        Button btn = new Button();
        btn.setText("Say \n'Hello World'");
        btn.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent event) {
                System.out.println("Hello");
            }
             
        });
        
        Button btn1 = new Button();
        btn1.setText("Horizontal");
        btn1.setOnAction(new EventHandler<ActionEvent>() {
            
            @Override
            public void handle(ActionEvent event) {
                tilePane.setOrientation(Orientation.HORIZONTAL);
            }
        });
        
        Button btn2 = new Button();
        btn2.setText("Vertical");
        btn2.setOnAction(new EventHandler<ActionEvent>() {
            
            @Override
            public void handle(ActionEvent event) {
                tilePane.setOrientation(Orientation.VERTICAL);
            }
        });
        
        tilePane.getChildren().addAll(btn1, btn, btn2);
        //set all button equal width and height
        ObservableList<Node> children = tilePane.getChildren();
        children.forEach(button->{
            ((Button)button).setMinWidth(Button.USE_PREF_SIZE);
            ((Button)button).setMaxWidth(Double.MAX_VALUE);
            ((Button)button).setMinHeight(Button.USE_PREF_SIZE);
            ((Button)button).setMaxHeight(Double.MAX_VALUE);
        });

        Scene scene = new Scene(tilePane, 300, 250);
        
        primaryStage.setTitle("java-buddy");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
    
}

No comments:

Post a Comment