如何在JavaFX中将按钮对齐到右下角?

twi*_*lco 4 java javafx

我是JavaFX的新手,我试图在scrapeBtn应用程序的右下角找到一个按钮(特别是).这是我到目前为止:

package main;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class Driver extends Application {

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

    @Override
    public void start(Stage primaryStage) {

        Button scrapeBtn = new Button();
        scrapeBtn.setText("Scrape!");
        scrapeBtn.setOnAction(new EventHandler<ActionEvent>() {

            public void handle(ActionEvent event) {
                System.out.println("Scrape button pressed.");
            }
        });

        TextField console = new TextField();

        GridPane root = new GridPane();    

        GridPane.setConstraints(scrapeBtn, 2, 2, 1, 1);
        root.getChildren().add(scrapeBtn);

        root.getChildren().add(console);

        Scene scene = new Scene(root, 600, 400);

        primaryStage.setTitle("Wiki Scraper");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

}
Run Code Online (Sandbox Code Playgroud)

关于如何实现这一目标的任何想法?一般来说,使用JavaFX对齐和格式化事物的一些技巧也非常受欢迎.

谢谢.

gfk*_*kri 6

我经常使用a BorderPane用于类似的目的(例如,在中心有一些文本和控件等的对话框,在底部有一个或多个按钮).因此,我使用BorderPaneas根和HBox底部的"按钮容器".最后,我将botton对齐设置为"RIGHT".

这是一个基于您的代码的示例:

@Override
public void start(Stage primaryStage) {

    // center
    VBox vbCenter = new VBox(); // use any container as center pane e.g. VBox
    TextField console = new TextField();
    vbCenter.getChildren().add(console);

    // bottom respectively "button area"
    HBox hbButtons = new HBox();
    Button scrapeBtn = new Button();
    scrapeBtn.setText("Scrape!");
    scrapeBtn.setOnAction(new EventHandler<ActionEvent>() {

      public void handle(ActionEvent event) {
        System.out.println("Scrape button pressed.");
      }
    });
    hbButtons.getChildren().add(scrapeBtn);
    hbButtons.setAlignment(Pos.CENTER_RIGHT);

    // root
    BorderPane root = new BorderPane();
    root.setPadding(new Insets(20)); // space between elements and window border
    root.setCenter(vbCenter);
    root.setBottom(hbButtons);

    Scene scene = new Scene(root, 600, 400);

    primaryStage.setTitle("Wiki Scraper");
    primaryStage.setScene(scene);
    primaryStage.show();
}
Run Code Online (Sandbox Code Playgroud)

此代码导致此问题(在稍微调整窗口大小后):

结果