Hi,

I'm creating an application that makes use of the GridBagLayout as it is the most useful layout manager for what I need. I made a JPanel and added it to the frame. The result I'm currently getting during run-time is a JFrame with a JPanel placed in the center. Now, I know that when using GridBagLayout all components are center aligned by default so I am trying to align my JPanel to the top-left of the frame. I have made many attempts at solving my problem including use of the lines: c.NORTHWEST; and also myJPanel.setLayout(0,0);
with no success. If possible would anyone be kind enough to assist me in resolving my problem? I have included a small amount of code that is not my own but is similar if it helps to visualize. Thank you.

public formGUI ()
	{
		super();
        this.setPreferredSize(new Dimension(600, 600));
        this.setSize(600,400);
       	this.setTitle("Application Title");
       	this.setLayout(new GridBagLayout());
       	GridBagConstraints c = new GridBagConstraints();
		

		
		MyPanel.setPreferredSize(new Dimension(400, 400));
		MyPanel.setBorder(BorderFactory.createTitledBorder("MainPanel"));
		MyPanel.setLayout(new GridBagLayout());
		c.fill = GridBagConstraints.VERTICAL;
		c.insets = new Insets(5,5,10,5);  //padding
		c.gridx = 0;
		c.gridy = 0;
		c.gridwidth = 1;
		c.gridheight = 1;
		c.weightx = 1.0;
		c.weighty = 1.0;
		this.add(MyPanel, c);

Problem has been solved...

How so? Please post your solution so that if someone comes across your thread in a search (or is just reading the thread like I am) they can see it.

This is my solution:

setLayout( new BorderLayout() );
GridBagLayout gridbag = new GridBagLayout();
JPanel frame = new JPanel(gridbag);
add(panel, BorderLayout.NORTH );

frame.add( ... ); // add your GridBagLayout Components to frame to align them to top

11 years later... I'm trying to solve a similar question, and your post is really ambiguous. Your giving methods (setLayout(new GridBagLayout())), without referencing whether you're setting the layout of the JFrame or the JPanel. Could you (or anyone for that matter), specify the instance you're applying those methods to? Thanks!

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.