I am using GridBagLayout to locate components on panel but it is not working like it has to be. Location of components is not affecting by changing x and y values somebody please help explain what mistake i am making here Thanks in advance :)
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.*;
public class LMS extends JFrame {
JPanel mainPanel;
JLabel RegNum, Name, FatherNam, MotherNam, DateBirth, BloodGrp, Email, Gender, RegDate, Desig, photo;
JTextField RegNuumText, FatherNamText, MotherNamText, EmailText, DesigText;
JList BloodGrpList;
JSpinner DateSpi;
// Constructor
public LMS() {
this.setTitle("Library Managment System");
this.setVisible(true);
this.setSize(700, 600);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
// this.setResizable(false);
mainPanel = new JPanel();
// GridBagLayout bag = new GridBagLayout();
mainPanel.setLayout(new GridBagLayout());
// Creating Labels
RegNum = new JLabel("Registration Number");
Name = new JLabel("Full Name");
FatherNam = new JLabel("Father's Name");
MotherNam = new JLabel("Mother's Name");
DateBirth = new JLabel("Date Of Birth");
BloodGrp = new JLabel("Blood Group");
Email = new JLabel("Email");
Gender = new JLabel("Gender");
RegDate = new JLabel("Registration Date");
Desig = new JLabel("Designation");
photo = new JLabel("Photo");
// creating Text Fields
RegNuumText = new JTextField(30);
FatherNamText = new JTextField();
MotherNamText = new JTextField();
EmailText = new JTextField();
DesigText = new JTextField();
// mainPanel.add(RegNum);
addComp(mainPanel, RegNum, 0, 0, 2, 1, GridBagConstraints.EAST, GridBagConstraints.NONE);
addComp(mainPanel, RegNuumText, 0, 1, 2, 1, GridBagConstraints.WEST, GridBagConstraints.NONE);
this.add(mainPanel);
}
private void addComp(JPanel thePanel, JComponent comp, int xPos,
int yPos, int compWidth, int compHeight, int place, int stretch) {
GridBagConstraints gridConstraints = new GridBagConstraints();
gridConstraints.gridx = xPos;
gridConstraints.gridy = yPos;
gridConstraints.gridwidth = compWidth;
gridConstraints.gridheight = compHeight;
gridConstraints.weightx = 1;
gridConstraints.weighty = 1;
gridConstraints.insets = new Insets(5, 5, 5, 5);
gridConstraints.anchor = place;
gridConstraints.fill = stretch;
thePanel.add(comp, gridConstraints);
}
public static void main(String[] args) {
new LMS();
}
}
GridBagLayout is not the easiest one, you have to play a little with it. Maybe these lines help you to achieve what you wanted. They will put the label in the upper left corner and the Textfield right behind it.
Note, that there are panels defined as place holders - they will fill the empty space.
addComp(mainPanel, RegNum, 0, 1, 1, 1, GridBagConstraints.WEST, GridBagConstraints.NONE);
addComp(mainPanel, RegNuumText, 1, 1, 1, 1, GridBagConstraints.WEST, GridBagConstraints.NONE);
addComp(mainPanel, new JPanel(), 2, 1, 1, 1, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL);
addComp(mainPanel, new JPanel(), 0, 2, 1, 1, GridBagConstraints.WEST, GridBagConstraints.VERTICAL);
You also need to change your helper method a little:
gridConstraints.weightx = stretch == GridBagConstraints.NONE || stretch == GridBagConstraints.VERTICAL ? 0 : 1;
gridConstraints.weighty = stretch == GridBagConstraints.NONE || stretch == GridBagConstraints.HORIZONTAL ? 0 : 1;
I think this should do the trick. Maybe you should define two or three helper methods, so you don't need to set all parameters every time. From my experience, very rarely you will need to define the anchor and only some times you might want to stretch components. Most of the time, for me, it is just puting stuff into the right bags (x, y, sometimes: width, height).
Edit: maybe it would help to put setVisible() at the end of the definition, not the beginning.
Related
I created this program that displays 2 photos and some facts (JLabel) about myself. However, the facts about myself are to the right of the pages. I would like the facts (JLabels) to be right under the pictures stacked, like a title and bullet points under the title, any help?
Ignore the import for sound. Eventually, I want the program to play a tune.
import java.awt.*;
import sun.audio.*;
import javax.swing.*;
public class AudioandImage extends JFrame {
public ImageIcon image1;
public JLabel label1;
public ImageIcon image2;
public JLabel label2;
public JLabel name;
public JLabel facts;
public JLabel born;
public JLabel es;
public JLabel sport;
public JLabel lastly;
AudioandImage() {
setLayout (new FlowLayout());
image1 = new ImageIcon(getClass().getResource("losangeles.jpg"));
label1 = new JLabel(image1);
add(label1);
image2 = new ImageIcon(getClass().getResource("elsalvador.jpg"));
label2 = new JLabel(image2);
add(label2);
name = new JLabel("My name is Erik Landaverde");
add(name);
facts = new JLabel("Some facts about myself:");
add(facts);
born = new JLabel("I was born and raised in South Central Los Angeles");
add(born);
es = new JLabel("Have a Salvadorean background");
add(es);
sport = new JLabel("My favorite sport is soccer");
add(sport);
lastly = new JLabel("Lastly... I am a programmer!");
add(lastly);
}
public static void main(String[] args) {
AudioandImage gui = new AudioandImage();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setVisible(true);
gui.pack();
gui.setTitle("A Little About Myself");
}
}
The desired result can be accomplished by assigning a different layout to your JFrame to FlowLayout() BorderLayout for example,
setLayout (new BorderLayout()); // asign layout to JFrame
add(label1,BorderLayout.PAGE_START); //Add JLabel 1 to Jframe
add(label2,BorderLayout.CENTER); //Add JLabel 2 to Jframe
name = new JLabel("<html><ul>My name is : Erik Landaverde "
+ "<li/>Some facts about myself: </li> "
+ "<li/>I was born and raised in South Central Los Angeles</li>"
+ "<li/>Have a Salvadorean background</li>"
+ "<li/>My favorite sport is soccer</li>"
+ "<li/>Lastly... I am a programmer!</li></ul></html>", SwingConstants.CENTER);
add(name,BorderLayout.PAGE_END); //Add JLabel 3 to Jframe
for the label in March added it into one because only contained what I
format strings with <html> </html> and line with <ul><li>content</li></ul>
Flow layout is not suited for the way you want to display the labels. See https://docs.oracle.com/javase/tutorial/uiswing/layout/flow.html for tutorial on flow layout.
You can also find tutorial to BorderLayout from above link. You could use this layout here. Create a JPanel with your labels using GridLayout with 1 column. Then place it in CENTER or SOUTH of the JFrame using BroderLayout.
Another approach could be to write your text as a single HTML and set it in JTextPane etc.
Use Below code for GridBagLayout
Test() {
setLayout(new GridBagLayout());
image1 = new ImageIcon(getClass().getClassLoader().getResource("image.jpg"));
label1 = new JLabel(image1);
add(label1, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.NORTHEAST, GridBagConstraints.BOTH,
new Insets(0, 0, 0, 0), 0, 0));
name = new JLabel("My name is Erik Landaverde");
add(name, new GridBagConstraints(0, 2, 1, 1, 1.0, 1.0, GridBagConstraints.NORTHEAST, GridBagConstraints.BOTH,
new Insets(0, 0, 0, 0), 0, 0));
facts = new JLabel("Some facts about myself:");
add(facts, new GridBagConstraints(0, 3, 1, 1, 1.0, 1.0, GridBagConstraints.NORTHEAST, GridBagConstraints.BOTH,
new Insets(0, 0, 0, 0), 0, 0));
born = new JLabel("I was born and raised in South Central Los Angeles");
add(born, new GridBagConstraints(0, 4, 1, 1, 1.0, 1.0, GridBagConstraints.NORTHEAST, GridBagConstraints.BOTH,
new Insets(0, 0, 0, 0), 0, 0));
es = new JLabel("Have a Salvadorean background");
add(es, new GridBagConstraints(0, 5, 1, 1, 1.0, 1.0, GridBagConstraints.NORTHEAST, GridBagConstraints.BOTH,
new Insets(0, 0, 0, 0), 0, 0));
sport = new JLabel("My favorite sport is soccer");
add(sport, new GridBagConstraints(0, 6, 1, 1, 1.0, 1.0, GridBagConstraints.NORTHEAST, GridBagConstraints.BOTH,
new Insets(0, 0, 0, 0), 0, 0));
lastly = new JLabel("Lastly... I am a programmer!");
add(lastly, new GridBagConstraints(0, 7, 1, 1, 1.0, 1.0, GridBagConstraints.NORTHEAST, GridBagConstraints.BOTH,
new Insets(0, 0, 0, 0), 0, 0));
}
public static void main(String[] args) {
Test gui = new Test();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setVisible(true);
gui.pack();
gui.setTitle("A Little About Myself");
}
I simply cannot get my JTextFields to align correctly. Right now the program looks like this:
.
Now the Assignment numbers are correctly aligned. However the Mark JTextfield starts under 7 and Weight JTextField starts under the last Mark.
Now what I want is for everything to correctly align. Meaning at Assignment 1 there are Mark and Weight JTextFields under the same row. This should go along all the way down to 7 ( or how many number of rows I choose).
Code:
public class test{
private static final Insets normalInsets = new Insets(10,10,0,10);
private static final Insets finalInsets = new Insets(10,10,10,10);
private static JPanel createMainPanel(){
GridBagConstraints gbc = new GridBagConstraints();
//Adding the JPanels. Panel for instructions
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
int gridy = 0;
//JLabel for the Instructions
JTextArea instructionTextArea = new JTextArea(5, 30);
instructionTextArea.setEditable(false);
instructionTextArea.setLineWrap(true);
instructionTextArea.setWrapStyleWord(true);
JScrollPane instructionScrollPane = new JScrollPane(instructionTextArea);
addComponent(panel, instructionScrollPane, 0, gridy++, 3, 1, finalInsets, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);
//JLabels for Assignment
JLabel label1 = new JLabel("Assignment");
label1.setHorizontalAlignment(JLabel.CENTER);
addComponent(panel, label1, 0, gridy, 1, 1, finalInsets,GridBagConstraints.CENTER,GridBagConstraints.HORIZONTAL);
//JLabel for Mark
JLabel label2 = new JLabel("Mark");
label2.setHorizontalAlignment(JLabel.CENTER);
addComponent(panel, label2, 1, gridy, 1, 1, finalInsets, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);
//JLabel for Weight.
JLabel label3 = new JLabel("Weight");
label3.setHorizontalAlignment(JLabel.CENTER);
addComponent(panel, label3, 2, gridy++, 1, 1, finalInsets, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);
//JLabel Number for the number list of assignments at the side.
for(int i = 1; i<=7; i++){
String kok = String.valueOf(i);
JLabel number = new JLabel(kok);
number.setHorizontalAlignment(JLabel.CENTER);
addComponent(panel, number, 0, gridy++, 1, 1, normalInsets, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);
}
//JTextfield for Mark
for(int i=0; i<7; i++){
JTextField mark = new JTextField(20);
mark.setHorizontalAlignment(JLabel.CENTER);
addComponent(panel, mark, 1, gridy++, 1, 1, normalInsets, GridBagConstraints.CENTER,GridBagConstraints.NONE);
}
//JTextfield for Weight
for(int i=0; i<7; i++){
JTextField weight = new JTextField(20);
weight.setHorizontalAlignment(JLabel.CENTER);
addComponent(panel, weight, 2, gridy++, 1, 1, normalInsets, GridBagConstraints.CENTER,GridBagConstraints.NONE);
}
return panel;
}
private static void addComponent(Container container, Component component, int gridx, int gridy, int gridwidth, int gridheight, Insets insets, int anchor, int fill ){
GridBagConstraints gbc = new GridBagConstraints(gridx, gridy, gridwidth, gridheight, 1.0D,1.0D,anchor,fill,insets,0,0);
container.add(component,gbc);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createMainPanel());
frame.pack();
frame.setVisible(true);
new test();
}
}
I'm a terrible new Java programmer so go easy please :).
UPDATE~~~~~
After running the `for` loops which add the `JLabels` and `JTextFields`, you will need to reset `gbc.gridy = 1`. This way the loop will start adding components from the top row.
//JLabel Number for the number list of assignments at the side.
for(int i = 1; i<=7; i++){
String kok = String.valueOf(i);
JLabel number = new JLabel(kok);
number.setHorizontalAlignment(JLabel.CENTER);
addComponent(panel, number, 0, gridy++, 1, 1, normalInsets, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);
}
gbc.gridy = 1;
//JTextfield for Mark
for(int i=0; i<7; i++){
JTextField mark = new JTextField(20);
mark.setHorizontalAlignment(JLabel.CENTER);
gridy = 1; //The code only partly works when I include this
addComponent(panel, mark, 1, gridy++, 1, 1, normalInsets, GridBagConstraints.CENTER,GridBagConstraints.NONE);
}
gbc.gridy = 1;
And this is what it looks like:
Only the Weight JTextField properly aligned. When I don't add 'gridy=1' it has the same format error as my original screenshot.
After running the for loops which add the JLabels and JTextFields, you will need to reset gbc.gridy = 2. This way the loop will start adding components from the top row. Also, in each use of addComponent(), change gridy++ to gbc.gridy++.
gbc.gridy = 2;
//JLabel Number for the number list of assignments at the side.
for(int i = 1; i<=7; i++){
String kok = String.valueOf(i);
JLabel number = new JLabel(kok);
number.setHorizontalAlignment(JLabel.CENTER);
addComponent(panel, number, 0, gbc.gridy++, 1, 1, normalInsets, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);
}
gbc.gridy = 2;
//JTextfield for Mark
for(int i=0; i<7; i++){
JTextField mark = new JTextField(20);
addComponent(panel, mark, 1, gbc.gridy++, 1, 1, normalInsets, GridBagConstraints.CENTER,GridBagConstraints.NONE);
}
gbc.gridy = 2;
//JTextfield for Weight
for(int i=0; i<7; i++){
JTextField weight = new JTextField(20);
weight.setHorizontalAlignment(JLabel.CENTER);
addComponent(panel, weight, 2, gbc.gridy++, 1, 1, normalInsets, GridBagConstraints.CENTER,GridBagConstraints.NONE);
}
This is what the result looks like:
I try to do a simple swing window, but with the layout it's not easy...
I mean I just want a window with 3 panels :
header with 20% of window in height
content with 60% of window in height
footer with 20% of window in height
But I can't succeed to have what I want. I used a gridLayout(3,1) but I can't specify the height.
public class Window extends JFrame implements Serializable {
private JPanel _header;
private JPanel _content;
private JPanel _footer;
public Window() {
GridLayout grid = new GridLayout(3,1);
setLayout(grid);
_header = new JPanel();
_header.setBackground(Color.GRAY);
getContentPane().add(_header);
_content = new JPanel();
JScrollPane jsp = new JScrollPane(_content, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
jsp.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
getContentPane().add(jsp);
_footer = new JPanel();
_footer.setBackground(Color.GRAY);
getContentPane().add(_footer);
pack();
validate();
setTitle("Chat client");
setVisible(true);
setSize(500, 500);
setLocationRelativeTo(null);
}
Can you help me ?
Best regards
GridBagLayout is capable of dividing vertical or horizontal space proportionally.
Here's an example that displays a red JPanel in the top 20% of a window, a green JPanel in the middle 60%, and a blue JPanel in the bottom 20%:
JFrame window = new JFrame();
window.setLayout(new GridBagLayout());
JPanel top = new JPanel(), middle = new JPanel(), bottom = new JPanel();
top.setBackground(Color.red);
middle.setBackground(Color.green);
bottom.setBackground(Color.blue);
GridBagConstraints c = new GridBagConstraints();
// we want the layout to stretch the components in both directions
c.fill = GridBagConstraints.BOTH;
// if the total X weight is 0, then it won't stretch horizontally.
// It doesn't matter what the weight actually is, as long as it's not 0,
// because the grid is only one component wide
c.weightx = 1;
// Vertical space is divided in proportion to the Y weights of the components
c.weighty = 0.2;
c.gridy = 0;
window.add(top, c);
// It's fine to reuse the constraints object; add makes a copy.
c.weighty = 0.6;
c.gridy = 1;
window.add(middle, c);
c.weighty = 0.2;
c.gridy = 2;
window.add(bottom, c);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
Result:
GridLayout always spaces evenly. You could instead use GridBagLayout, the most evil of all the Java layout managers. I've given them "weights" of 20, 60, 20 so you can see which values are which. You can just as easily use 2, 6, 2, it doesn't matter it's just a ratio. Look at the GridBagLayout tutorial for more info.
Example
public class Window extends JFrame implements Serializable {
private JPanel _header;
private JPanel _content;
private JPanel _footer;
public Window() {
GridBagLayout grid = new GridBagLayout();
setLayout(grid);
_header = new JPanel();
_header.setBackground(Color.GRAY);
// <=== add with constraints here
getContentPane().add(_header, new GridBagConstraints(0, 0, 1, 1, 1, 20, GridBagConstraints.BASELINE, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
_content = new JPanel();
JScrollPane jsp = new JScrollPane(_content, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
jsp.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
// <=== add with constraints here
getContentPane().add(jsp, new GridBagConstraints(0, 1, 1, 1, 1, 60, GridBagConstraints.BASELINE, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
_footer = new JPanel();
_footer.setBackground(Color.GRAY);
// <=== add with constraints here
getContentPane().add(_footer, new GridBagConstraints(0, 2, 1, 1, 1, 20, GridBagConstraints.BASELINE, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
pack();
validate();
setTitle("Chat client");
setVisible(true);
setSize(500, 500);
setLocationRelativeTo(null);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Window();
}
});
}
}
Screenshot
I'm learning how to use GridBagLayout. I created two buttons in a JFrame. I tried making it that one of them occupies one collumn (the default), and the other two collumns, thus being twice the size of the first one (I know I can acheive this using setPrefferredSize, but my intention is to learn how to use gridwidth and gridheight).
What's the problem? Thanks
import java.awt.*;
import javax.swing.*;
public class Main extends JFrame {
Main(){
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(500,500);
JPanel panel1 = new JPanel(new GridBagLayout());
JButton b1,b2;
b1 = new JButton("button 1");
b2 = new JButton("button 2");
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridwidth = 1;
panel1.add(b1);
gbc.gridx = 2;
gbc.gridwidth = 2;
panel1.add(b2);
add(panel1);
setVisible(true);
}
public static void main(String[]args){
Main m = new Main();
}
}
It doesn't matter how many columns the second button's width.
Actually both buttons will be asked for their preferred width and the width will be set to them if it's enough space for them.
If it's less space then min width is used.
If there is extra space it's distributed between controls according to weights proportions.
You can try to set iPadX=100 for the first and iPadx=200 and set proportion iPadX=1 for the first and iPadx=2 for the second.
The problem is that all the columns of a GridBagLayout don't have the same width. The widths are computed based on the preferred size of the components they contain. So, you could use 3, 4 or 100 as the gridwidth for the second button, it wouldn't change anything.
You need to use fillx and weightx to change the way the buttons resize.
Try using GridBagConstraint in this way, hope this will help you.
import java.awt.*;
import javax.swing.*;
public class Main extends JFrame {
Main(){
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(500,500);
JPanel panel1 = new JPanel(new GridBagLayout());
JButton b1,b2;
b1 = new JButton("button 1");
b2 = new JButton("button 2");
panel1.add(b1, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
panel1.add(b2, new GridBagConstraints(1, 0, 1, 1, 2.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
add(panel1);
setVisible(true);
}
public static void main(String[]args){
Main m = new Main();
}
}
EDIT
Or change in your code Like this below:
gbc.gridx = 1;
gbc.gridwidth = 1;
panel1.add(b1, gbc);
gbc.gridx = 2;
gbc.gridwidth = 2;
gbc.fill = gbc.HORIZONTAL; //set fill property to HORIZONTAL
gbc.weightx= 2.0;
panel1.add(b2, gbc); //While adding button also add it with gbc
I want to make an input form in Java so that the user can enter details.
Something like this:
My code
import java.awt.GridLayout;
import javax.swing.*;
class JOptionPaneTest {
public static void main(String[] args) {
String[] items = {"One", "Two", "Three", "Four", "Five"};
JComboBox combo = new JComboBox(items);
JTextField field1 = new JTextField("1234.56");
JTextField field2 = new JTextField("9876.54");
JPanel panel = new JPanel(new GridLayout(0, 1));
panel.add(combo);
panel.add(new JLabel("Field 1:"));
panel.add(field1);
panel.add(new JLabel("Field 2:"));
panel.add(field2);
int result = JOptionPane.showConfirmDialog(null, panel, "Test",
JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
if (result == JOptionPane.OK_OPTION) {
System.out.println(combo.getSelectedItem()
+ " " + field1.getText()
+ " " + field2.getText());
} else {
System.out.println("Cancelled");
}
}
}
My output form:
I think I must change my layout to something like BorderLayout. Any ideas how to get the look of the form at the top of the question?
Yes, you have to change layout. Have a look at SpringLayout and this example:
(source: sun.com)
String[] labels = {"Name: ", "Fax: ", "Email: ", "Address: "};
int numPairs = labels.length;
//Create and populate the panel.
JPanel p = new JPanel(new SpringLayout());
for (int i = 0; i < numPairs; i++) {
JLabel l = new JLabel(labels[i], JLabel.TRAILING);
p.add(l);
JTextField textField = new JTextField(10);
l.setLabelFor(textField);
p.add(textField);
}
//Lay out the panel.
SpringUtilities.makeCompactGrid(p,
numPairs, 2, //rows, cols
6, 6, //initX, initY
6, 6); //xPad, yPad
SpringLayout works fine for this simple form, but there is third party libraries that has more features. I.e. MiG Layout.
Another way to create a form using GridBagLayout, producing the following result:
Code:
JPanel addressPanel = new JPanel();
Border border = addressPanel.getBorder();
Border margin = new EmptyBorder(10, 10, 10, 10);
addressPanel.setBorder(new CompoundBorder(border, margin));
GridBagLayout panelGridBagLayout = new GridBagLayout();
panelGridBagLayout.columnWidths = new int[] { 86, 86, 0 };
panelGridBagLayout.rowHeights = new int[] { 20, 20, 20, 20, 20, 0 };
panelGridBagLayout.columnWeights = new double[] { 0.0, 1.0, Double.MIN_VALUE };
panelGridBagLayout.rowWeights = new double[] { 0.0, 0.0, 0.0, 0.0, 0.0,
Double.MIN_VALUE };
addressPanel.setLayout(panelGridBagLayout);
addLabelAndTextField("City:", 0, addressPanel);
addLabelAndTextField("Street:", 1, addressPanel);
addLabelAndTextField("State:", 2, addressPanel);
addLabelAndTextField("Phone:", 3, addressPanel);
addLabelAndTextField("Mail:", 4, addressPanel);
The helper method addLabelAndTextField:
private void addLabelAndTextField(String labelText, int yPos,
Container containingPanel) {
JLabel label = new JLabel(labelText);
GridBagConstraints gridBagConstraintForLabel = new GridBagConstraints();
gridBagConstraintForLabel.fill = GridBagConstraints.BOTH;
gridBagConstraintForLabel.insets = new Insets(0, 0, 5, 5);
gridBagConstraintForLabel.gridx = 0;
gridBagConstraintForLabel.gridy = yPos;
containingPanel.add(label, gridBagConstraintForLabel);
JTextField textField = new JTextField();
GridBagConstraints gridBagConstraintForTextField = new GridBagConstraints();
gridBagConstraintForTextField.fill = GridBagConstraints.BOTH;
gridBagConstraintForTextField.insets = new Insets(0, 0, 5, 0);
gridBagConstraintForTextField.gridx = 1;
gridBagConstraintForTextField.gridy = yPos;
containingPanel.add(textField, gridBagConstraintForTextField);
textField.setColumns(10);
}
You are currently using a GridLayout, which can be fine for your need.
However, you should initialize it with the actual number of rows and columns you will need. In your case:
new GridLayout(0, 2);
0 for rows means there is not limit, and you have 2 columns, one for the labels, and one for the input component. See the Java tutorial for more information on GridLayouts.
(source: sun.com)
Note however that the GridLayout will make all "cells" to be the same size, which can be a problem for the labels.
However, Jonas is right, a SpringLayout is probably more adapted to your need.
You can do this with DesignGridLayout. The following snippet should work (sorry I could not test it I am not on my dev station right now):
DesignGridLayout layout = new DesignGridLayout(panel);
layout.row().grid(streetAddressLabel).add(streetAddressField);
layout.row().grid(cityLabel).add(cityField);
layout.row().grid(stateLabel).add(stateSpinner);
layout.row().grid(zipLabel).add(zipField);
layout.emptyRow();
layout.row().right().add(setAddressButton, clearAddressButton);
Then you would use JDialog (rather than JOptionPane) to display your panel.