组件使用flowlayout,但我使用的是GridBagLayouts

时间:2014-03-17 03:07:07

标签: java swing

我的组件正在排列,就像它们在流程图中一样。我为它们添加了约束,但它似乎没有跟随它们,原因是什么。我想我可能会意外地将flowlayout纳入某处,但我不知道在哪里。

代码:

    BorderLayout borderLayout = new BorderLayout();
       setLayout(borderLayout);
    //Initialize labels, text field, and combo box
     enterFirstName = new JLabel ("First Name");
     firstName = new JTextField();
     enterLastName = new JLabel ("Last Name");
     lastName = new JTextField();
     enterId = new JLabel ("Identification");
     identification = new JTextField();
     enterAddress = new JLabel("Address");
     streetAddress = new JTextField();
     enterCity = new JLabel("City");
     city = new JTextField();
     selectState = new JLabel("State");
     state = new JComboBox();
     enterZip = new JLabel("Zip Code");
     zipCode = new JTextField();
     enterPhone = new JLabel("Phone Number");
     phoneNumber = new JTextField();




    //Initialize buttons
     goBack = new JButton ("Go Back");
     purchase = new JButton ("Complete Purchase");
     cancel = new JButton ("Cancel");



     //making the grid thing
     dataPane = new JPanel(new GridBagLayout());

     GridBagConstraints c = new GridBagConstraints();

     c.fill = GridBagConstraints.HORIZONTAL;
     c.gridx = 0;
     c.gridy = 0;
     dataPane.add(enterFirstName);
     c.fill = GridBagConstraints.HORIZONTAL;
     c.gridx = 1;
     c.gridy = 0;
     dataPane.add(firstName);
     c.gridx = 0;
     c.gridy = 1;
     dataPane.add(enterLastName);

     dataPane.add(enterLastName);

     buttonPane = new JPanel();

     buttonPane.add(goBack);
     buttonPane.add(purchase);
     buttonPane.add(cancel);
     add(dataPane);
     add(buttonPane, BorderLayout.SOUTH);

}
}

1 个答案:

答案 0 :(得分:2)

您没有为组件提供约束......

 GridBagConstraints c = new GridBagConstraints();

 c.fill = GridBagConstraints.HORIZONTAL;
 c.gridx = 0;
 c.gridy = 0;
 dataPane.add(enterFirstName); // ?? No constraints...
 //...
 dataPane.add(firstName);
 //...
 dataPane.add(enterLastName);
 // No idea why this is here...
 dataPane.add(enterLastName);

确保提供您想要使用的约束...

 dataPane.add(enterFirstName, gbc);

请查看How to Use GridBagLayout了解更多详情......