GroupLayout:组件没有按原样布局?

时间:2014-01-03 18:19:06

标签: java swing grouplayout

组件应该像这样布置:

(A)
  + ------------------- +
  | label1 textfield1 |
  | label2 textfield2 |
  | label3 textfield3 |
  + ------------------- +

但他们现在的样子是:

(B)
 + ------------------------------------------------- -------- +
 | label1 label2 label3 textfield1 textfield2 textfield3 |
 + ------------------------------------------------- -------- +

如何使它们看起来像( A

SSCCE代码:

import java.awt.Dimension;
import javax.swing.GroupLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class GroupLayoutTest extends JPanel
{

   GroupLayout layout;
   JTextField tf_id;
   JTextField tf_name;
   JTextField tf_price;
   JLabel lb_id;
   JLabel lb_name;
   JLabel lb_price;

   public GroupLayoutTest()
   {
      layout = new GroupLayout(this);
      layout.setAutoCreateGaps(true);
      layout.setAutoCreateContainerGaps(true);

      lb_id = new JLabel("id");
      lb_name = new JLabel("name");
      lb_price = new JLabel("price");

      tf_id = new JTextField(5);
      tf_name = new JTextField(5);
      tf_price = new JTextField(5);
      createGUI();
   }

   private void createGUI()
   {
      layout.setHorizontalGroup(
              layout.createSequentialGroup()
              .addGroup(layout.createParallelGroup()
                      .addComponent(lb_id)
                      .addComponent(lb_name)
                      .addComponent(lb_price))
              .addGroup(layout.createParallelGroup()
                      .addComponent(tf_id)
                      .addComponent(tf_name)
                      .addComponent(tf_price))
      );

      layout.setVerticalGroup(
              layout.createSequentialGroup()
              .addGroup(layout.createParallelGroup()
                      .addComponent(lb_id)
                      .addComponent(tf_id))
              .addGroup(layout.createParallelGroup()
                      .addComponent(lb_name)
                      .addComponent(tf_name))
              .addGroup(layout.createParallelGroup()
                      .addComponent(lb_price)
                      .addComponent(tf_price)
              ));
   }

   @Override
   public Dimension getPreferredSize()
   {
      return new Dimension(400, 500);
   }

   public void creatAndShowGUI()
   {
      JFrame frame = new JFrame();
      frame.add(this);
      frame.pack();
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setVisible(true);
   }

   public static void main(String[] args)
   {
      javax.swing.SwingUtilities.invokeLater(new Runnable()
      {

         @Override
         public void run()
         {
            GroupLayoutTest test = new GroupLayoutTest();
            test.creatAndShowGUI();
         }
      });
   }

}

1 个答案:

答案 0 :(得分:2)

您可以正确设置布局,但是忘记将其添加到面板中。因此,在代码中的某处添加行this.setLayout(layout);,它应该可以正常工作。