当我将GridLayout设置为JPanel然后添加内容时,它随后以“文本顺序”(从左到右,从上到下)添加。但我想在特定单元格中添加一个元素(在第j列的第i行)。有可能吗?
答案 0 :(得分:42)
不,您无法在特定单元格中添加组件。您可以做的是添加空的JPanel对象并在数组中保持对它们的引用,然后以您想要的任何顺序向它们添加组件。
类似的东西:
int i = 3;
int j = 4;
JPanel[][] panelHolder = new JPanel[i][j];
setLayout(new GridLayout(i,j));
for(int m = 0; m < i; m++) {
for(int n = 0; n < j; n++) {
panelHolder[m][n] = new JPanel();
add(panelHolder[m][n]);
}
}
然后,您可以直接添加到其中一个JPanel对象:
panelHolder[2][3].add(new JButton("Foo"));
答案 1 :(得分:5)
是
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,HorizontalGap,VerticleGap)
(new GridLayout(2,2,1,1))=&gt;在这里,我想要2行,2列, - 如果有任何水平间隙(HGap),它们应该是1px(1单位)
- 我也想要相同的垂直间隙所以我做同垂直间隙(VGap)。即1个单位
- 在这种情况下; gap =&gt;间距/边距/填充 - 在这种意义上。
创建您的组件并将其添加到面板
- (分量,0,0)=&gt; 0,0是行和列..(就像一个2d数组)。 @row 0&amp; @column 0或在第0行和第0列的交叉点
通过将行和列放在应该去的位置来指定组件的位置。
每个单元格都有一个位置== [row] [column]
或者你可以不用hgaps和vgaps来做到这一点:
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(2,2));
JButton component= new JButton("Component");
panel.add(component, 0,0 );