【问题标题】:Gridlayout only adds elements vertically, not horizontallyGridlayout 仅垂直添加元素,而不是水平添加元素
【发布时间】:2012-11-20 02:02:56
【问题描述】:

我正在为我正在创建的一个简单游戏制作关卡编辑器,在关卡编辑器中,我希望有一些在网格上对齐的按钮和标签。几乎是 gridlayout 的设计目的。

以下代码出于某种我无法理解的邪恶原因,仅在彼此下方添加元素,如下所示:

地图宽度:

地图高度:

地图深度:

它-应该-看起来像这样:

地图宽度:地图高度:

地图深度:

我已经尝试了一个小时,但我很困惑,这不应该像让它工作那样花费太多的努力,但确实如此。

    private void drawUiElements()
{
    int xLoc = (int) (dim.width * 0.75);
    int yLoc = 0;
    int width = (int) (dim.width * 0.25);
    int height = dim.height;

    JPanel buttonContainer = new JPanel();
    buttonContainer.setLayout(new GridLayout(16, 2, 5, 5));
    buttonContainer.setBounds(xLoc, yLoc, width, height);
    buttonContainer.setName("buttonContainer");

    JLabel labelx = new JLabel("Map Width:");
    JLabel labely = new JLabel("Map Height:");
    JLabel labelz = new JLabel("Map Depth:");

    buttonContainer.add(labelx, "1");
    buttonContainer.add(labely, "2");
    buttonContainer.add(labelz, "3");

    add(buttonContainer);
}

谢谢。

【问题讨论】:

    标签: java grid-layout


    【解决方案1】:

    使用GridLayout 时,您无法将组件添加到特定单元格。您可以将初始行数设置为0,以便填充组件rows-first

    buttonContainer.setLayout(new GridLayout(0, 2, 5, 5));
    

    见:How to Use GridLayout

    【讨论】:

    • 但是 api 指定组件是先添加行,而不是先添加列。 docs.oracle.com/javase/6/docs/api(图一)
    • 这仅在您指定初始行数为0 时才有效,以便在重新计算布局之前首先填充所有可能的行。查看更新
    猜你喜欢
    • 1970-01-01
    • 2012-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-12
    • 2016-07-27
    • 2012-11-10
    • 1970-01-01
    相关资源
    最近更新 更多