[英]How to automatically resize buttons on BorderPane as the window is resized?
要將按鈕對准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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.