Hi
This is a code for placing a few labels.
Now, I have a problem with my grid.
I want the 0,0 point in the upper left corner but at the moment it is around the middle.
Can someone help me please?

import javax.swing.*;
import java.awt.*;
public class test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		JFrame frame = new JFrame("test");
		frame.setSize(500, 500);
		frame.setVisible(true);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		JPanel panel = new JPanel(new GridBagLayout());
		panel.setLocation(0, 0);
		panel.setBackground(Color.pink);
		frame.add(panel);
		frame.getContentPane().add(panel,BorderLayout.PAGE_START);
		//
		GridBagConstraints c = new GridBagConstraints();
		//JLabel lbl0 = new JLabel("0");
		//c.gridx = -1;
		//c.gridy = -1;
		//panel.add(lbl0,c);
		JLabel lbl1 = new JLabel("1");
		c.gridx = 0;
		c.gridy = 0;
		c.insets = new Insets(10, 10, 10, 10);
		panel.add(lbl1,c);
		JLabel lbl2 = new JLabel("2");
		c.gridx = 1;
		c.gridy = 1;
		panel.add(lbl2,c);
		JLabel lbl3 = new JLabel("3"); 
		c.gridx = 2;
		c.gridy = 2;
		panel.add(lbl3,c);
		JLabel lbl4 = new JLabel("4"); 
		c.gridx = 3;
		c.gridy = 3;
		panel.add(lbl4,c);
		JLabel lbl5 = new JLabel("5"); 
		c.gridx = 4;
		c.gridy = 4;
		panel.add(lbl5,c);
	}

}

Recommended Answers

All 3 Replies

Take a look at the anchor property.

Edit: You'll also need to look at the weightx property. You can read about it in the general notes for the GridBagLayout class.

commented: I love GBL. ;-) +15
commented: both contstrains +1 +9

Take a look at the anchor property.

Edit: You'll also need to look at the weightx property. You can read about it in the general notes for the GridBagLayout class.

And weighty, of course (if he wants the upperleft, otherwise he'll just get the left. ;-)

commented: Yes, and weighty too ;) +15
commented: both contstrains +1 +9

I'm going to try it

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.