如何从上到下然后从左到右填充GridLayout?

sky*_*ork 4 java swing awt layout-manager grid-layout

a的默认行为GridLayout是组件逐行填充,从左到右填充.我想知道我是否可以使用它以便组件由列填充(从左到右)?谢谢.

aio*_*obe 5

GridLayout管理器不支持此类用例.

我建议你看看GridBagLayout,它允许你通过GridBagConstraints.gridx和设置位置GridBagConstraints.gridy.

(要获得类似的行为,请GridLayout务必设置权重并正确填充.)


Sta*_*avL 5

您可以扩展GridLayout并覆盖一个方法而不是int i = r * ncols + c;使用int i = c * nrows + r;我认为这就足够了.

public void layoutContainer(Container parent) {
  synchronized (parent.getTreeLock()) {
    Insets insets = parent.getInsets();
    int ncomponents = parent.getComponentCount();
    int nrows = rows;
    int ncols = cols;
    boolean ltr = parent.getComponentOrientation().isLeftToRight();

    if (ncomponents == 0) {
        return;
    }
    if (nrows > 0) {
        ncols = (ncomponents + nrows - 1) / nrows;
    } else {
        nrows = (ncomponents + ncols - 1) / ncols;
    }
    int w = parent.width - (insets.left + insets.right);
    int h = parent.height - (insets.top + insets.bottom);
    w = (w - (ncols - 1) * hgap) / ncols;
    h = (h - (nrows - 1) * vgap) / nrows;

    if (ltr) {
        for (int c = 0, x = insets.left ; c < ncols ; c++, x += w + hgap) {
        for (int r = 0, y = insets.top ; r < nrows ; r++, y += h + vgap) {
            int i = r * ncols + c;
            if (i < ncomponents) {
            parent.getComponent(i).setBounds(x, y, w, h);
            }
        }
        }
    } else {
        for (int c = 0, x = parent.width - insets.right - w; c < ncols ; c++, x -= w + hgap) {
        for (int r = 0, y = insets.top ; r < nrows ; r++, y += h + vgap) {
            int i = r * ncols + c;
            if (i < ncomponents) {
            parent.getComponent(i).setBounds(x, y, w, h);
            }
        }
        }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)