JavaFX: Making the previous example simpler

This entry is part 11 of 55 in the series JavaFX

We have a HBox and a VBox in the previous example. Let’s take away the Hbox and look at how we set up the list for display.

In line 21, we create an object border with a size of 500 x 400.

In line 33, we have a VBox method addVbox that help us to set up a vbox object as shown in line 35.

In the addVbox method, we have a list with the stated items and note how the items have to be added to the list using

list.setItems(items);

Once the list has been set up with the items, we have to add the list to the vbox using

vbox.getChildren().add(list);
VBox with List
package javafxapplication9;

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.control.ListView;
import javafx.stage.Stage;

public class JavaFXApplication9 extends Application {

    @Override
    public void start(Stage stage) {

        BorderPane border = new BorderPane();

        border.setPrefSize(500, 400);

        border.setRight(addVBox());

        Scene scene = new Scene(border);
        stage.setScene(scene);
        stage.setTitle("Layout Sample");
        stage.show();
    }

    private VBox addVBox() {

        VBox vbox = new VBox();
        vbox.setPadding(new Insets(10)); // Set all sides to 10
        vbox.setSpacing(8);              // Gap between nodes

        Text title = new Text("Top 5 Rock Albums");
        title.setFont(Font.font("Arial", FontWeight.BOLD, 14));
        vbox.getChildren().add(title);

        ListView<String> list = new ListView<String>();
        ObservableList<String> items = FXCollections.observableArrayList(
                "Like A Rolling Stone", "Archtung Baby", "Help!", "Smell Like Teen Spirit", "Hotel California");
        list.setItems(items);

        vbox.getChildren().add(list);

        return vbox;
    }

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

vbox2

Series Navigation<< JavaFX: BorderPane and VBox
JavaFX: Putting StackPane in HBox >>

Leave a comment

Leave a Reply