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);

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

Edited 6 Years Ago by sorsimmanis: n/a

This question has already been answered. Start a new discussion instead.