要在 BorderPane 底部的中心对齐按钮,一种简单方便的方法是使用 HBox 作为两个按钮的父容器。
HBox box = new HBox(10, button1, button2); // 10 is spacing
box.setAlignment(Pos.CENTER);
borderPane.setBottom(box);
由于您希望在扩展屏幕时扩展按钮,因此您可以将这些按钮的 HGROW 设置为Priority.ALWAYS
.
HBox.setHgrow(button1, Priority.ALWAYS);
HBox.setHgrow(button2, Priority.ALWAYS);
您还必须maxSize
通过调用从按钮中删除约束:
button1.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE);
button2.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE);
这种方法有一个小问题。这些按钮将捕获整个可用区域,我们不希望这样。摆脱它的一种简单方法是在 HBox 的开头和结尾添加两个固定长度的透明矩形。
MCVE
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
Button button1 = new Button("Button 1");
Button button2 = new Button("Button 2");
button1.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE);
button2.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE);
Rectangle rect1 = new Rectangle(60, 20);
rect1.setFill(Color.TRANSPARENT);
Rectangle rect2 = new Rectangle(60, 20);
rect2.setFill(Color.TRANSPARENT);
HBox box = new HBox(10, rect1, button1, button2, rect2);
box.setAlignment(Pos.CENTER);
HBox.setHgrow(button1, Priority.ALWAYS);
HBox.setHgrow(button2, Priority.ALWAYS);
BorderPane root = new BorderPane();
root.setBottom(box);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Main Stage");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}