温馨提示×

​Java HorizontalAlign类怎么使用

小亿
95
2023-10-21 17:48:42
栏目: 编程语言

Java中没有内置的HorizontalAlign类,但是可以通过使用JavaFX的HorizontalAlignment类来实现水平对齐。下面是一个使用JavaFX水平对齐的示例代码:

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.scene.paint.Color;
import javafx.stage.Stage;

public class HorizontalAlignExample extends Application {

    @Override
    public void start(Stage stage) {
        // 创建一个HBox容器
        HBox hbox = new HBox();
        hbox.setPadding(new Insets(10));
        hbox.setSpacing(10);
        hbox.setAlignment(Pos.CENTER);

        // 创建两个按钮并添加到HBox容器中
        Button button1 = new Button("Button 1");
        Button button2 = new Button("Button 2");
        hbox.getChildren().addAll(button1, button2);

        // 创建一个Scene并将HBox容器设置为根节点
        Scene scene = new Scene(hbox, 300, 200);
        scene.setFill(Color.LIGHTGRAY);

        // 将Scene设置到Stage中并显示Stage
        stage.setScene(scene);
        stage.setTitle("Horizontal Align Example");
        stage.show();
    }

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

在上面的代码中,我们创建了一个HBox容器,并设置了padding为10像素,spacing为10像素,alignment为Pos.CENTER(居中对齐)。然后创建了两个按钮,并将它们添加到HBox容器中。最后,创建了一个Scene,并将HBox容器设置为根节点,将Scene设置到Stage中并显示Stage。运行代码,你将看到两个居中对齐的按钮显示在窗口中。

0