JavaFX 2 Layouts: javafx.scene.layout.HBox

The javafx,scene.layout.HBox class arranges its child nodes in a single horizontal row.

Below is a simple program that demonstrates the

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.HBox;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.stage.Stage;

public class LayoutsHBox extends Application {
  
  @Override
  public void start(Stage primaryStage) {
    HBox root = new HBox();
    
    root.getChildren().addAll(new Label("Label 1"),
                              new TextField());
    
    Scene scene = new Scene(root, 200, 20);
    
    primaryStage.setTitle("HBox");
    primaryStage.setScene(scene);
    primaryStage.show();
  }

Below is the output from execution of the above program.

Like the VBox class, the HBox class can be a child node of another layout class to create sophisticated interfaces. The example program below is a variation of the program used in the post JavaFX 2.1 Layouts: javafx.scene.layout.VBox

import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
 
public class LayoutsHBox extends Application {
   
  @Override
  public void start(Stage primaryStage) {
    BorderPane root = new BorderPane();
    HBox top = new HBox();
    HBox bottom = new HBox();
    
    top.getChildren().addAll(new Label("Label 1"),
                             new TextField());
    bottom.getChildren().addAll(new Label("Label 1"),
                                new TextField());
    
    Label rtLbl = new Label("Right");
    Label lftLbl = new Label("Left");   
    Label cLbl   = new Label("Center");
      
    root.setTop(top);
    root.setAlignment(top, Pos.CENTER);
    root.setBottom(bottom);
    root.setAlignment(bottom, Pos.CENTER);
    root.setRight(rtLbl);
    root.setAlignment(rtLbl, Pos.CENTER);
    root.setCenter(cLbl);
    root.setLeft(lftLbl);
    root.setAlignment(lftLbl, Pos.CENTER);
     
    Scene scene = new Scene(root, 200, 200);
     
    primaryStage.setTitle("HBox");
    primaryStage.setScene(scene);
    primaryStage.show();
  }
}

Here is the output from the above program.

Leave a Reply

Your email address will not be published. Required fields are marked *