我正在使用oracle docs中的以下示例:
JComponent panel = ...;
GroupLayout layout = new GroupLayout(panel);
panel.setLayout(layout);
// Turn on automatically adding gaps between components
layout.setAutoCreateGaps(true);
// Turn on automatically creating gaps between components that touch
// the edge of the container and the container.
layout.setAutoCreateContainerGaps(true);
// Create a sequential group for the horizontal axis.
GroupLayout.SequentialGroup hGroup = layout.createSequentialGroup();
// The sequential group in turn contains two parallel groups.
// One parallel group contains the labels, the other the text fields.
// Putting the labels in a parallel group along the horizontal axis
// positions them at the same x location.
//
// Variable indentation is used to reinforce the level of grouping.
hGroup.addGroup(layout.createParallelGroup().
addComponent(label1).addComponent(label2));
hGroup.addGroup(layout.createParallelGroup().
addComponent(tf1).addComponent(tf2));
layout.setHorizontalGroup(hGroup);
// Create a sequential group for the vertical axis.
GroupLayout.SequentialGroup vGroup = layout.createSequentialGroup();
// The sequential group contains two parallel groups that align
// the contents along the baseline. The first parallel group contains
// the first label and text field, and the second parallel group contains
// the second label and text field. By using a sequential group
// the labels and text fields are positioned vertically after one another.
vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE).
addComponent(label1).addComponent(tf1));
vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE).
addComponent(label2).addComponent(tf2));
layout.setVerticalGroup(vGroup);
以下是该网站的链接:http://docs.oracle.com/javase/8/docs/api/javax/swing/GroupLayout.html
这个例子接近顶部。这是应该发生的事情:
"这"因为每行都有一个关联JComponent的标签。我想把它扩展到3,4,5 ......行。我尝试通过添加以下行添加更多行:
hGroup.addGroup(layout.createParallelGroup().
addComponent(label3).addComponent(label4));
hGroup.addGroup(layout.createParallelGroup().
addComponent(tf3).addComponent(tf4));
vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE).
addComponent(label3).addComponent(tf3));
vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE).
addComponent(label4).addComponent(tf4));
然而,这就是我所得到的:
我在左侧剪掉了它,但是你可以看到有4个文本字段和4个其他组件。文本字段应始终在彼此之下以及组件之间对齐。
我遗失了GroupLayout
或SequentialGroup
的内容,因为按照我的方式添加更多组件似乎非常简单。