【问题标题】:Is there a way to "autofit" elements on a page so they take up the entire canvas有没有办法在页面上“自动调整”元素,以便它们占据整个画布
【发布时间】:2022-01-25 05:55:06
【问题描述】:

在 JavaFX 中,有没有一种方法可以“自动调整”页面上的元素,以便它们占据整个页面?

目前,我正在尝试让窗口有两个按钮一起占据整个画布,但我不知道该怎么做,因为可以拉伸窗口等。我试过了玩弄Button.setPrefSize,但按钮大小保持不变,它只是显示一个带有两个超大按钮的窗口,其中的文本不可见。

我目前拥有的

我想要的(但对于任何窗口大小)

【问题讨论】:

  • 目前我正在使用 Flowpane,但如果有更好的方法来做到这一点,那也没关系。
  • button.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE)。研究:tips for sizing and slinging nodes 以及该教程中有关布局窗格的其他信息。
  • 编辑问题以添加其他信息,而不是编写 cmets。以minimal reproducible example 的形式提供您的代码。
  • Canvas 在 JavaFX 中的意思(研究一下),尽量使用准确的术语。

标签: java javafx


【解决方案1】:

这是一种方法(此处的代码,但也可以在 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();
    }
}

【讨论】:

    猜你喜欢
    • 2021-03-16
    • 1970-01-01
    • 1970-01-01
    • 2021-12-05
    • 1970-01-01
    • 2021-05-30
    • 2019-07-04
    • 2021-04-27
    • 1970-01-01
    相关资源
    最近更新 更多