2

我只想要一个 GridLayout 来合并单元格。所以我找到了 GridBagLayout。看起来这种布局非常灵活。我不需要这种灵活性。有没有办法告诉 GridBagLayout 它应该在整个宽度和高度上使用 20 列和 10 行?它应该看起来像一个 GridLayout,但具有合并单元格。

谢谢

4

2 回答 2

1

据我所知,您可以将相同的高度和宽度用于多个JComponent. 但是你必须改变它们,你想要一个合并的单元格。

这是一个如何使用 GridBagLayout的示例

protected void makebutton(String name,
                          GridBagLayout gridbag,
                          GridBagConstraints c) {
    Button button = new Button(name);
    gridbag.setConstraints(button, c);
    add(button);
}

public void init() {
    GridBagLayout gridbag = new GridBagLayout();
    GridBagConstraints c = new GridBagConstraints();
    setFont(new Font("SansSerif", Font.PLAIN, 14));
    setLayout(gridbag);
    c.fill = GridBagConstraints.BOTH;
    c.weightx = 1.0;
    makebutton("Button1", gridbag, c); 
    makebutton("Button2", gridbag, c);
    makebutton("Button3", gridbag, c);
    c.gridwidth = GridBagConstraints.REMAINDER; //end row
    makebutton("Button4", gridbag, c);

    c.weightx = 0.0;                //reset to the default
    makebutton("Button5", gridbag, c); //another row
    .........
}

所以你不需要一直指定高度和宽度。

于 2012-07-14T10:43:41.470 回答
0

我希望这是可能的,因为它会使我的项目更容易。然而,这就是答案:

GridBagLayout 没有提供明确定义网格中的行数或列数的方法,也没有定义网格中每个单元格大小的方法。相反,GridBagLayout 通过放置在屏幕上的组件数来计算网格中的行数和列数。如果一个容器有五个水平排列的组件,则网格由五列和一行组成。如果容器有五个垂直排列的组件,那么网格由一列和五行组成。

我从:http ://www2.sys-con.com/itsg/virtualcd/java/archives/0304/tabbone/index.html

对于我的项目,我正在考虑创建我的 GridBagLayout 的顶行和左列,其中 x 和 y 数量为 1 像素 x 1 像素透明面板,以手动创建类似 excel 的网格并将对象放入该网格结构中,使用 gridwidth和 gridheight 根据需要合并单元格。这应该让我可以轻松地创建复杂的布局并正确调整所有内容(敲木头)。

于 2015-01-05T21:16:54.720 回答