How to align the items in a form (grid layout)?
I need to place JLabels and JTextFields in a panel and align them as a form:
Name: <text field>
Surname: <text field>
Address: <textfield>
etc.
I'm trying to use GridLayout.
Quote:
panel1.setLayout(new GridLayout(1,2));
It works, but the spaces between labels and text fields are very big. How to make them smaller?
Or maybe I should us a different layout for that?
Please help
Re: How to align the items in a form (grid layout)?
If worse comes to worse, you could always use method setLocation(int width, int height);
Re: How to align the items in a form (grid layout)?
Thank you for the reply.
What is the usual way to make a simple form like that:
Name: <text field>
Initial: <text field>
Surname: <text field>
???
Re: How to align the items in a form (grid layout)?
You could try using nested JPanels,
Code :
private void controlHelper(){ //call this in constructor or w/e
JPanel controlPanel = new JPanel(); //control uses default layout manager
controlPanel.add(createPanelLabels());
controlPanel.add(PanelFields());
add(controlPanel, BorderLayout.SOUTH);
}
public JPanel createPanelLabels() {
JPanel p = new JPanel();
p.setLayout(new GridLayout(3, 1));
name = new JLabel("Name:");
initial = new JLabel("Initial:");
surname = new JLabel("Surname:");
p.add(name);
p.add(initial);
p.add(surname);
return p;
}
public JPanel panelFields() {
JPanel p = new JPanel();
p.setLayout(new GridLayout(3, 1));
final int FIELD_WIDTH = 10;
nameField = new JTextField("", FIELD_WIDTH);
//etc
}
This means that they will be side by side label - field, and squashed in, then you can define where you want it with something like BorderLayout.WEST and so forth.
That quick code needs to be worked on, as in, making an instance variable of nameField etc.
I hope thats what you're after, I'm a learner myself, just trying to contribute :).
Re: How to align the items in a form (grid layout)?
I recommend nesting panels in panels, like newbie suggested. The trick is to figure out what layout managers to put in each.
Check out this: A Visual Guide to Layout Managers
If you are having trouble doing this in code, you might want to try a GUI based builder. NetBeans is a free IDE written by Sun for writing java and it has a GUI tool to help you layout components, like Visual Basic sort of. Eclipse may have something similar now - I am not sure.
Sometimes I cheat and use NetBeans, and look at the resulting code to see how they did it, and then write my own using that info.