Saturday, December 29, 2012

How to Create Fully-Occupied-Space Controls in JavaFX

A simple example to create fully-occupied-space buttons in JavaFX.
package javafxapp;

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonBuilder;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.AnchorPaneBuilder;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.scene.layout.VBoxBuilder;
import javafx.stage.Stage;

public class JavaFXApp extends Application {
    @Override
    public void start(Stage primaryStage) throws Exception {
        primaryStage.setTitle("JavaFX App");
        
        BorderPane root = new BorderPane();
        
        root.setLeft(createNode("Left"));
        root.setRight(createNode("Right"));
        root.setCenter(createNode("Center"));
        root.setTop(createNode("Top"));
        root.setBottom(createNode("Bottom"));
        
        Scene scene = new Scene(root);
        
        primaryStage.setScene(scene);
        primaryStage.show();
    }
    
    private Node createNode(String text) {
        VBox vbox = VBoxBuilder.create()
            .spacing(5)
            .padding(new Insets(10, 10, 10, 10))
            .build();

        Button btn = ButtonBuilder.create()
            .text(text)
            .build();
        
        AnchorPane anchoredPane = AnchorPaneBuilder.create()
            .children(btn)
            .style("-fx-border-style: solid;"
                + "-fx-border-width: 1;"
                + "-fx-border-color: black")
                .build();
        
        AnchorPane.setBottomAnchor(btn, 5.0);
        AnchorPane.setRightAnchor(btn, 5.0);
        AnchorPane.setTopAnchor(btn, 5.0);
        AnchorPane.setLeftAnchor(btn, 5.0);
        
        VBox.setVgrow(anchoredPane, Priority.ALWAYS);
        vbox.getChildren().addAll(anchoredPane);
        
        return vbox;
    }
    
    public static void main(String[] args) {
        launch(args);
    }
}

No comments:

Post a Comment