Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Why are my anchors not working in GridBagLayout?

843807Aug 14 2008 — edited Aug 14 2008
Hi,
I've always had this problem and have had to find workarounds for it and finally I have written some code to explain what I mean. The code below simply creates a JFrame with two labels in, and although I set the anchor for the labels to go to page start and page end they just stick in the middle. Can anyone see what I am doing wrong and how I can get the labels to go to the top and bottom of the component, many thanks, Anthony.
import java.awt.*;

import javax.swing.*;

public class TestGridBag extends JFrame {

	public TestGridBag() {
		JPanel contentPanel = new JPanel();
		contentPanel.setBorder( BorderFactory.createLineBorder( Color.black ) );
		GridBagLayout gbLayout = new GridBagLayout();
		GridBagConstraints gbConstraints = new GridBagConstraints();
		contentPanel.setLayout(gbLayout);
		
		JLabel topLabel = new JLabel( "topLabel" );
		JLabel bottomLabel = new JLabel( "bottomLabel" );
		
		gbConstraints.anchor = GridBagConstraints.PAGE_START;
		gbConstraints.gridheight = 1;
		gbConstraints.gridwidth = 1;
		gbConstraints.gridx = 0;
		gbConstraints.gridy = 0;
		gbLayout.setConstraints( topLabel, gbConstraints );
		contentPanel.add( topLabel );
		
		gbConstraints.anchor = GridBagConstraints.PAGE_END;
		gbConstraints.gridheight = 1;
		gbConstraints.gridwidth = 1;
		gbConstraints.gridx = 0;
		gbConstraints.gridy = 1;
		gbLayout.setConstraints( bottomLabel, gbConstraints );
		contentPanel.add( bottomLabel );
		
		this.getContentPane().add( contentPanel );
		this.setSize(400, 400);
		this.setVisible(true);
	}

	public static void main(String args[]) {
		new TestGridBag();
	}
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Sep 11 2008
Added on Aug 14 2008
2 comments
1,040 views