在 JavaFX 中,有沒有辦法“自動調整”頁面上的元素,使它們占據整個頁面?
目前,我試圖讓視窗有兩個按鈕,它們一起占據整個畫布,但我不知道該怎么做,因為可以拉伸視窗等。我試過玩Button.setPrefSize,但按鈕大小保持不變,它只顯示一個帶有兩個超大按鈕的視窗,其中的文本不可見。
我目前擁有的

我想要什么(但對于任何視窗大小)

uj5u.com熱心網友回復:
這是一種方法(此處的代碼,但也可以在 Scene Builder 和 FXML 中使用):
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.stage.Stage;
public class TestApplication extends Application {
@Override
public void start(Stage stage) throws Exception {
Button button1 = new Button("Button1");
HBox.setHgrow(button1, Priority.SOMETIMES);
button1.setMaxWidth(Double.MAX_VALUE);
button1.setMaxHeight(Double.MAX_VALUE);
Button button2 = new Button("Button2");
HBox.setHgrow(button2, Priority.SOMETIMES);
button2.setMaxWidth(Double.MAX_VALUE);
button2.setMaxHeight(Double.MAX_VALUE);
HBox hBox = new HBox(button1, button2);
AnchorPane.setLeftAnchor(hBox, 0.0);
AnchorPane.setRightAnchor(hBox, 0.0);
AnchorPane.setTopAnchor(hBox, 0.0);
AnchorPane.setBottomAnchor(hBox, 0.0);
AnchorPane rootContainer = new AnchorPane(hBox);
Scene scene = new Scene(rootContainer, 600, 600);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch();
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/392763.html
