JavaFX: Setting Constraints On Children

This entry is part 8 of 55 in the series JavaFX

In the previous example, we have the label and text overlapping each other.  Stackpane provides a static method to set positioning constraint on its children.

Let’s apply this constraint to the label.

In this example, we set the label to the TOP_CENTER position of the stackpane.

Notice how I have also set the color of the label.

package javafxapplication8;
 
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.stage.Stage;
 
public class JavaFXApplication8 extends Application {
 
    @Override
    public void start(Stage primaryStage) {
 
        primaryStage.setTitle("JavaFX Program");
 
        StackPane stackpane = new StackPane();
 
        Scene scene = new Scene(stackpane, 300, 250);
        primaryStage.setScene(scene);
 
        Label lb = new Label();
        lb.setFont(Font.font("Times New Roman", 24));
        lb.setText("Hello World");
        lb.setTextFill(Color.web("#0076a3"));
        StackPane.setAlignment(lb, Pos.TOP_CENTER);
         
        stackpane.getChildren().add(lb);

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

p1

Series Navigation<< JavaFX: Stackpane and z-order
JavaFX: BorderPane class >>

Leave a comment

Leave a Reply