【问题标题】:Fill entire scene with buttons JavaFX用按钮 JavaFX 填充整个场景
【发布时间】:2016-04-29 00:16:30
【问题描述】:

我正在尝试处理一个 VBox,我想用最多 5 个包含最多 5 个按钮的 HBox 填充该 VBox。 我还需要这些按钮可以调整大小,但我无法完成。 已经尝试使用返回 HBox 的静态方法,从

调用它
primaryStage.getChildren.addAll(hBoxMethod());

非常感谢您的帮助:)

【问题讨论】:

  • 请告诉我们您尝试了什么

标签: java javafx


【解决方案1】:

不完全确定您尝试做什么。但是,如果您尝试使用 5x5 自动调整大小的按钮(如标题所示)填充您的屏幕:为什么不使用 GridPane 和 AnchorPanes 的组合来调整大小。

package sample;

import javafx.application.Application;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.*;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        AnchorPane rootPane = new AnchorPane();
        Scene scene = new Scene(rootPane, 400, 300);

        GridPane grid = new GridPane();
        MaximizeInAnchorPane(grid);

        // make column and rows resize
        for (int i=0;i <5;i++)
        {
            ColumnConstraints cConstrain = new ColumnConstraints();
            cConstrain.setHgrow(Priority.SOMETIMES);
            grid.getColumnConstraints().add(cConstrain);

            RowConstraints rConstrain = new RowConstraints();
            rConstrain.setVgrow(Priority.SOMETIMES);
            grid.getRowConstraints().add(rConstrain);
        }

        for (int i=0;i <5;i++)
        {
            for (int j=0;j <5;j++)
            {
                // create button and put it in an AnchorPane, that will resize it
                AnchorPane buttonPane = new AnchorPane();
                Button button = new Button("Button");
                MaximizeInAnchorPane(button);
                buttonPane.getChildren().add(button);

                grid.add(buttonPane,i,j);
            }
        }

        rootPane.getChildren().add(grid);
        primaryStage.setTitle("test");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private static void MaximizeInAnchorPane(Node toMaximize)
    {
        AnchorPane.setTopAnchor(toMaximize, 0.0);
        AnchorPane.setRightAnchor(toMaximize, 0.0);
        AnchorPane.setLeftAnchor(toMaximize, 0.0);
        AnchorPane.setBottomAnchor(toMaximize, 0.0);
    }

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

如果您尝试手动调整所有内容的大小,您应该看看 SplitPane。这完全取决于您要调整大小的方式。

对我来说,使用 JavaFX Scene Builder JavaFX Scene Builder 弄清楚如何做我想要的布局总是有帮助的。

【讨论】:

  • 每个按钮代表商店提供的产品,位于数据库中,已分类。例如,销售员选择销售苏打水,那么屏幕上就会显示商店所有的苏打水,比如可口可乐、雪碧等。问题是不会总是有 25 种产品,但我将其设置为限制如果有超过 25 个,这不太可能,除非它们没有被很好地分类。感谢您的回答,我将尝试操作 de 嵌套 for,以便仅添加所需的按钮数量。
猜你喜欢
  • 1970-01-01
  • 2019-04-02
  • 2016-05-06
  • 2015-02-04
  • 2014-06-07
  • 2018-04-29
  • 2017-08-08
  • 2014-12-13
  • 1970-01-01
相关资源
最近更新 更多