GridLayout中的组件无法正确显示

时间:2013-12-23 07:51:04

标签: java swing jframe layout-manager grid-layout

我创建了一个包含2行和3列的GridLayout框架。我把3个JLabel放在第一行和每一列。当我尝试运行时,第三个标签位于第二行,第一个列位于下面

screenshot

为什么会这样?

这里是代码

  JFrame windows = new JFrame("Shop");
  windows.setLayout(new GridLayout(2,3));
  JLabel prodlabel = new JLabel("Products");
  windows.add(prodlabel);
  JLabel spacelabel = new JLabel(" mid ");
  windows.add(spacelabel);
  JLabel shoplabel = new JLabel("Shopping List");
  windows.add(shoplabel);
  windows.setSize(1360, 728);
  windows.setVisible(true);

3 个答案:

答案 0 :(得分:1)

当行和列都设置为非零值时,它与GridLayout的行为方式有关。 LayoutManager根据行数和容器的组件计数决定列数本身。

您可以将行数设置为0并将列设置为3.在向容器添加更多组件时,LayoutManager将添加更多行。

windows.setLayout(new GridLayout(0,3));

修改:措辞和here's a link to the Java Tutorial on GridLayout which may or may not have more information related to the matter.

答案 1 :(得分:0)

这是因为您使用GridLayout将组件调整到整个单元格(垂直/水平),当您向其添加组件时,它会逐个放置组件,首先将组件放入行,然后将它们切换到列已满。您需要使用其他LayoutManager

例如,尝试使用GridBagLayout

或者您可以使用一行new GridLayout(1,3)来修复它。

答案 2 :(得分:0)

您可以为6个元素设置布局。 尝试添加所有6个元素并运行它