我正在尝试使用GroupLayout进行以下操作:
-------------------------------
- label1: aLongTextfield1 -
- label2: checkbox1 -
- checkbox2 -
- accept cancel -
-------------------------------
label1和label2具有结尾对齐。 aLongTextfield1,checkbox1和checkbox2具有最前面的对齐方式,接受和取消按钮应位于尾部,以便取消按钮位于右边缘。
代码如下:
GroupLayout layout = new GroupLayout(this);
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);
setLayout(layout);
layout.setHorizontalGroup(
layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.TRAILING)
.addComponent(nameLabel)
.addComponent(evaluatorLabel)
.addComponent(boundingBoxLabel))
.addGroup(layout.createParallelGroup()
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(nameField)
.addComponent(landCheckBox)
.addComponent(shallowCheckBox)
.addComponent(waterCheckBox)
.addComponent(deepCheckBox)
.addComponent(boundingBoxArea))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addComponent(createButton)
.addComponent(cancelButton)))));
layout.setVerticalGroup(
layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(nameLabel)
.addComponent(nameField))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(evaluatorLabel)
.addComponent(landCheckBox))
.addComponent(shallowCheckBox)
.addComponent(waterCheckBox)
.addComponent(deepCheckBox)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(boundingBoxLabel)
.addComponent(boundingBoxArea,
GroupLayout.PREFERRED_SIZE,
GroupLayout.DEFAULT_SIZE,
GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(createButton)
.addComponent(cancelButton)));
// Make the bottom buttons the same size
layout.linkSize(SwingConstants.HORIZONTAL, createButton, cancelButton);
运行此命令时,接受和取消按钮在复选框的左边缘对齐,但是我希望它们在框架的右边缘对齐。我可以通过将按钮放在单独的面板中,然后使用BorderLayout在PAGE_END处添加按钮来解决此问题,但我认为必须在GroupLayout中实现所有这些操作。
已解决
水平组中的第二组应具有TRAILING对齐方式。水平组中的按钮组应该是顺序的。
layout.setHorizontalGroup(
layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.TRAILING)
.addComponent(label1)
.addComponent(label2))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.TRAILING)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(aLongTextField)
.addComponent(checkBox1)
.addComponent(checkBox2))
.addGroup(layout.createSequentialGroup()
.addComponent(acceptButton)
.addComponent(cancelButton))));