组布局连续三个元素

时间:2018-03-13 16:02:40

标签: java swing user-interface grouplayout

以下是我在布局中添加元素的方法

GroupLayout layout = new GroupLayout(panel);
    layout.setAutoCreateGaps(true);
    layout.setAutoCreateContainerGaps(true);
    panel.setLayout(layout);

    layout.setHorizontalGroup(
        layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(GroupLayout.Alignment.TRAILING))
                .addComponent(socSecIconLabel)
                .addComponent(creditCardIconLabel)
            .addGroup(layout.createParallelGroup(GroupLayout.Alignment.TRAILING))
                .addComponent(socSecLabel)
                .addComponent(creditCardLabel)
            .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING))
                .addComponent(socSecCheck)
                .addComponent(creditCardCheck)
    );

    layout.setVerticalGroup(
        layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE))
                .addComponent(socSecIconLabel)
                .addComponent(socSecLabel)
                .addComponent(socSecCheck)
            .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE))
                .addComponent(creditCardIconLabel)
                .addComponent(creditCardLabel)
                .addComponent(creditCardCheck)
    );

我的目标是每行中的icon label :: label ::复选框,但是使用此代码我只会搞乱:

not in the row

如何对齐每行中的元素?

2 个答案:

答案 0 :(得分:0)

以下是使用GridLayout,两行四列的示例:

import java.awt.*;
import javax.swing.*;

public class GridLayoutExample extends JFrame {

    public void addComponents(final Container pane) {
        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(2,4)); //2 rows, 4 columns

        panel.add(new JLabel("Social security"));
        panel.add(new JButton("Click 1"));
        panel.add(new JCheckBox(""));
        panel.add(new JTextField());

        panel.add(new JLabel("Credit card"));
        panel.add(new JButton("Click 2"));
        panel.add(new JCheckBox(""));
        panel.add(new JTextField());

        pane.add(panel);
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                GridLayoutExample frame = new GridLayoutExample();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.addComponents(frame.getContentPane());
                frame.pack();
                frame.setVisible(true);
            }
        });
    }
}

enter image description here

答案 1 :(得分:0)

您的想法正确,但我认为问题在于每个ad​​dGroup末尾的多余)。代替

.addGroup(layout.createParallelGroup(GroupLayout.Alignment.TRAILING))
            .addComponent(socSecIconLabel)

尝试

.addGroup(layout.createParallelGroup(GroupLayout.Alignment.TRAILING)
            .addComponent(socSecIconLabel)

您的代码会将组件添加到“通用​​”组,而不是您创建的特定并行组。