2011-06-30 53 views

回答

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

我認爲這是一個可怕的想法,除非你對'preferredLayoutSize','minimumLayoutSize'等做同樣的事情。 – aioobe

+0

我不這麼認爲。如果你看一下計算,你可以看到它們只是計算組件的最大尺寸並相應地在行/列上相乘。 – StanislavL

+0

啊,好點! +1給你。 :-) – aioobe

2

你不能用一個單一的GridLayout實現這一目標。但是,您可以在一行中有一個GridLayout,每個單元具有包含多行的單列的GridLayout。雖然使用不同的LayoutManager如TableLayout可能是一個更容易的選擇。

1

我建議你試試MigLayout。您可以切換流動方向:

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

這裏有很多方式與MigLayout來實現這一點,我覺得這麼多友好比GridBagLayout的使用,只是爲能夠,如果不是更多的話。您不再需要BorderLayout,FlowLayout,BoxLayout等,MigLayout也可以做到這一點。

相關問題