2010-03-24 24 views

回答

38

不,您不能在特定的單元格中添加組件。你可以做的是添加空的JPanel對象,並保持數組中的引用,然後以任何你想要的順序向它們添加組件。

喜歡的東西:

​​3210

後來的後來,你可以直接添加到JPanel的對象之一:

panelHolder[2][3].add(new JButton("Foo")); 
+1

或者,如果你不依賴於'GridLayout',您可以使用[ 'GridBagLayout'](http://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html) – bluefoot

4

JPanel panel = new JPanel(); 
    panel.setLayout(new GridLayout(2,2,1,1)); 
    JButton component= new JButton("Component"); 
    panel.add(component, 0,0); 

創建面板,將其佈局。
新的GridLayout(numberOfRows,numberOfColums,horizo​​ntalGap的,VerticleGap)

(新的GridLayout(2,2,1,1))=  這裏我想2行,2列,
> - 如果任何水平差距(HGap),它們應該是1px(1unit)
- 我也希望垂直差距相同,所以我的垂直差距相同(VGap)。即1個單位
- 在這種情況下;差距  =>距離/邊距/填充 - 在這個意義上。

創建組件,並將它們添加到面板
- (組分,0,0)  => 0,0是行和列..(如二維數組)。
通過將行和列放在應該走的位置來指定組件的位置。
每個單元都有一個位置== [行] [列]

或者你可以不用hgaps和vgaps:

JPanel panel = new JPanel();   
    panel.setLayout(new GridLayout(2,2)); 
    JButton component= new JButton("Component"); 
    panel.add(component, 0,0); 
相關問題