使用 GridLayout 时,我可以将组件添加到特定的网格单元格吗? [英] Can I add a component to a specific grid cell when a GridLayout is used?

查看:33
本文介绍了使用 GridLayout 时,我可以将组件添加到特定的网格单元格吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我将 GridLayout 设置为 JPanel 然后添加一些内容时,它会按文本顺序"(从左到右,从上到下)随后添加.但我想将一个元素添加到特定单元格(在第 j 列的第 i 行中).可能吗?

When I set the GridLayout to the JPanel and then add something, it is added subsequently in the "text order" (from left to right, from top to bottom). But I want to add an element to a specific cell (in the i-th row in the j-th column). Is it possible?

推荐答案

不,您不能在特定单元格中添加组件.您可以做的是添加空的 JPanel 对象并在数组中保留对它们的引用,然后按您想要的任何顺序向它们添加组件.

No, you can't add components at a specific cell. What you can do is add empty JPanel objects and hold on to references to them in an array, then add components to them in any order you want.

类似于:

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 对象之一:

Then later, you can add directly to one of the JPanel objects:

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

这篇关于使用 GridLayout 时,我可以将组件添加到特定的网格单元格吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆