4

我正在尝试制作一个两列三行的布局。类似于以下内容:

----------------------
| Username |Textbox| |
| Email    |Textbox| |
----------------------

然而,即使我很确定这些组管理正确,它仍然会像这样在一行中结束: 单行

我将垂直组分开就好了

gl_contentPanel.setHorizontalGroup(
        gl_contentPanel.createSequentialGroup()
                  .addGroup(gl_contentPanel.createParallelGroup(GroupLayout.Alignment.LEADING)
                           .addComponent(usernameLabel)
                           .addComponent(emailLabel))
                  .addGroup(gl_contentPanel.createParallelGroup(GroupLayout.Alignment.LEADING)
                           .addComponent(usernames)
                           .addComponent(email))
             );
        gl_contentPanel.setVerticalGroup(
                gl_contentPanel.createSequentialGroup()
                   .addGroup(gl_contentPanel.createParallelGroup(GroupLayout.Alignment.BASELINE)
                        .addComponent(usernameLabel)
                        .addComponent(usernames))
                   .addGroup(gl_contentPanel.createParallelGroup(GroupLayout.Alignment.BASELINE)
                        .addComponent(emailLabel)
                        .addComponent(email))
             );

有任何想法吗?

4

2 回答 2

4

您需要设置容器的布局 - 请参阅下面第三行中的标记 [1]。在我看来,您似乎错过了这一点,并且容器使用了 FlowLayout。

JFrame frame = new JFrame("GroupLayout Test");
GroupLayout gl_contentPanel = new GroupLayout(frame.getContentPane());
frame.setLayout(gl_contentPanel); // [1]

JLabel usernameLabel = new JLabel("User name");
JLabel emailLabel = new JLabel("Email");
JTextField usernames = new JTextField("usernames");
JTextField email = new JTextField("email");

// your snippet
gl_contentPanel.setHorizontalGroup(
        gl_contentPanel.createSequentialGroup()
                  .addGroup(gl_contentPanel.createParallelGroup(GroupLayout.Alignment.LEADING)
                               .addComponent(usernameLabel)
                               .addComponent(emailLabel))
                      .addGroup(gl_contentPanel.createParallelGroup(GroupLayout.Alignment.LEADING)
                               .addComponent(usernames)
                               .addComponent(email))
                 );
    gl_contentPanel.setVerticalGroup(
            gl_contentPanel.createSequentialGroup()
               .addGroup(gl_contentPanel.createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(usernameLabel)
                    .addComponent(usernames))
               .addGroup(gl_contentPanel.createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(emailLabel)
                    .addComponent(email))
         );
// end of your snippet

frame.pack();
frame.setVisible(true);
于 2012-07-01T18:43:11.713 回答
3

作为参考,这里有一个两列三行布局的工作示例,如下图所示,可能有助于指导您。

图片

于 2012-07-01T19:08:00.867 回答