📜  JavaFX hbox(1)

📅  最后修改于: 2023-12-03 15:31:35.607000             🧑  作者: Mango

JavaFX HBox

JavaFX HBox is a layout container that arranges its children nodes horizontally in a single row. It is a part of JavaFX UI toolkit that helps in creating rich desktop applications with modern UI elements.

Creating an HBox

To create an HBox, you need to import the javafx.scene.layout.HBox class and instantiate it as follows:

HBox hbox = new HBox();
Adding Children Nodes

You can add children nodes to the HBox using the getChildren() method. For example:

Button button1 = new Button("Button 1");
Button button2 = new Button("Button 2");
Button button3 = new Button("Button 3");

hbox.getChildren().addAll(button1, button2, button3);
HBox Properties

The HBox class provides several properties that you can use to customize the appearance and behavior of the container. Some of the commonly used properties are:

Spacing

You can set the spacing between the children nodes using the setSpacing() method. For example:

hbox.setSpacing(10);
Alignment

You can set the alignment of the children nodes using the setAlignment() method. For example:

hbox.setAlignment(Pos.CENTER);
Padding

You can set the padding around the container using the setPadding() method. For example:

hbox.setPadding(new Insets(10, 20, 10, 20));
Example

Here's an example that creates an HBox with three buttons and sets the spacing, alignment, and padding:

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class HBoxExample extends Application {

    @Override
    public void start(Stage primaryStage) {
        HBox hbox = new HBox();
        hbox.setSpacing(10);
        hbox.setAlignment(Pos.CENTER);
        hbox.setPadding(new Insets(10, 20, 10, 20));

        Button button1 = new Button("Button 1");
        Button button2 = new Button("Button 2");
        Button button3 = new Button("Button 3");

        hbox.getChildren().addAll(button1, button2, button3);

        primaryStage.setScene(new Scene(hbox, 300, 100));
        primaryStage.show();
    }
}
Conclusion

JavaFX HBox is a simple and powerful layout container that allows you to easily arrange your UI elements horizontally. With its flexible properties, you can customize it to your liking and create modern and beautiful desktop applications.