This is the first tutorial in JavaFX 2.0 Layouts series and this topic provides an overview and a simple example of HBox JavaFX 2.0 layout. HBox lays out its children in a single horizontal row. If the HBox has a border and/or padding set, then the contents will be layed out within those insets.
Our simple HBox example will contain 4 buttons without any functionality to keep it simple, because goal is to understand how HBox layout works. Here you can look how our example will look at the end.
- Open Eclipse IDE
- Create a new Java Project and specify name HBoxTest
- Add jfxrt.jar from Project -> Properties -> Java Build Path -> Libraries -> Add External Jars
- Create class inside this project with name HBoxMain
Here is code for HBox example.
//HBox HBox hb = new HBox(); hb.setPadding(new Insets(15, 12, 15, 12)); hb.setSpacing(10);First we create an instance of a HBox. The padding is the top, right, bottom, and left spacing around the region's content in pixels. The amount of horizontal space between each child in the hbox.
//Buttons Button btn1 = new Button(); btn1.setText("Button1"); hb.getChildren().add(btn1);
Here we create button and set text, and add it to HBox layout. Repeat this step for all of buttons.
And at the end we need to add HBox layout to the Scene, and set the scene to primary stage, and show that primary stage.
//Adding HBox to the scene Scene scene = new Scene(hb); primaryStage.setScene(scene); primaryStage.show();If you have any comments, questions, and anything like that, please feel free to a leave comment below.
If you like this, and other JavaFX 2 tutorials on this blog, you can follow me on Twitter to be informed about new JavaFX tutorials.