How to put my check box under my text fields in Swing?
I have a text field to represent a name, and a combobox for registration type. Then, next to that I have a check box, but it's supposed to be underneath the other two fields. Here is what I have coded:
public RegPanel()
{
//create a new panel
new GridLayout(2,1);
//create one of two subpanels
subPanel = new JPanel(new FlowLayout());
//create a textfield
regTextField = new JTextField(20);
//create a combobox and don't let anyone add to it
regComboBox = new JComboBox(regOptions);
//create a border for the subpanel
subPanel.setBorder(BorderFactory.createTitledBorder("Registrant's Name & Type"));
//add regTypePanel and regBox to the panel
subPanel.add(regTextField);
subPanel.add(regComboBox);
//create a second subpanel with a flowlayout
subPanel2 = new JPanel(new FlowLayout());
//create a checkbox
regCheckBox = new JCheckBox("Dinner and Keynote Speech");
subPanel2.add(regCheckBox);
//add the subpanels to the main panel
add(subPanel);
add(subPanel2);
}
Any ideas what I am missing? Sorry for the crappy layout, I can't figure out how to fix the view.
So I realized I hadn't set the GridLayout right, so I changed that to "setLayout(new GridLayout(2,1)); But now on my gu开发者_开发技巧i, it totally screwed up the position of all the other elements.
Anyway new GridLayout(...)
do nothing unless you use it in setLayout(...)
.
You can try using Box.createVerticalBox() (sample) instead of GridLayout to have your components in vertical alignment.
In your case, you are using
- RegPanel (which layout?)
- subPanel (FlowLayout)
- regTextField
- regComboBox
- subPanel2 (FlowLayout)
- regCheckBox
- subPanel (FlowLayout)
Which layout does your main RegPanel have? It has the default JPanel layout (if RegPanel is a subclass of JPanel), which is a FlowLayout. So, your RegPanel shows the two subPanels besides each other, which looks similar as if you had only one Panel with all the components. So, your RegPanel needs a LayoutManager, too - the GridLayout(2,1) seems okay (if you don't want to align the components in the two lines).
In my current project, I'm only ever using GroupLayout
(apart from one occasional BorderLayout). It takes a bit to get used to (and a wrapper class to make the code easier to write and read), but for such form stuff, it seems ideal (when limited to the build-in Layout managers).
Also you might want to use a BorderLayout and realize that you nest one layout in another layout to achieve a different effect.
Have to mention MigLayout here as a great all-purpose layout manager -- it is extremely flexible and easy to use once you get to know it.
精彩评论