Thursday, May 10, 2012

JavaFX 2.0 Layouts: HBox

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.

Before we start coding we need to do following steps:
  1. Open Eclipse IDE
  2. Create a new Java Project and specify name HBoxTest
  3. Add jfxrt.jar from  Project -> Properties -> Java Build Path -> Libraries -> Add External Jars
  4. Create class inside this project with name HBoxMain

If you still have problem with that take a look at Getting Started with JavaFX 2.0 in Eclipse IDE.

Here is code for HBox example.

    HBox hb = new HBox();
    hb.setPadding(new Insets(15, 12, 15, 12));

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.
 Button btn1 = new Button();

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);

If you have any comments, questions, and anything like that, please feel free to a leave comment below. 

Check other tutorial from JavaFX 2 Layout series by clicking on the image above.

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.


Post a Comment