2011-06-30 10 views

答えて

5

int i = r * ncols + c;の代わりに の代わりにint i = c * nrows + r;という方法を1つだけオーバーライドすれば十分です。

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); 
      } 
     } 
     } 
    } 
    } 
} 
+0

'preferredLayoutSize'、' minimumLayoutSize'などで同じことをしない限り、それはひどい考えです。 – aioobe

+0

私はそうは思わない。計算を見ると、コンポーネントの最大サイズが計算され、それに応じて行/列が掛け合わされることがわかります。 – StanislavL

+0

ああ、良い点!あなたに+1してください。 :-) – aioobe

5

このようなユースケースは、GridLayoutマネージャではサポートされていません。

代わりにGridBagLayoutをご覧になることをお勧めします。GridBagConstraints.gridxGridBagConstraints.gridyで位置を設定できます。

GridLayoutと同様の挙動が重みを設定し、適切に必ず記入して取得すること。)

2

あなたは、単一のGridLayoutでこれを達成することはできません。ただし、各セルに複数列の単一列のGridLayoutがある1行のGridLayoutを持つことができます。 TableLayoutのような別のLayoutManagerを使用する方が簡単です。

1

お試しになることをお勧めします。MigLayoutあなたはと流れの方向を切り替えることができます

setLayout(new MigLayout("flowy")); 
add(component1); 
add(component2); 
add(component3, "wrap"); 
add(component4); 
add(component5); 
add(component6); 

MigLayoutでこれを達成するための多くの方法がありますが、私はそれがそんなに優しいのGridBagLayoutよりも使用するようにと同じように可能であり、そうでない場合よりそう見つけます。 BorderLayout、FlowLayout、BoxLayoutなどはもう必要ありません.MyLayoutもそれをすべて行います。

関連する問題