aspose file tools*
The moose likes Swing / AWT / SWT and the fly likes Panel Appearing in Centre using GridBagLayout Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Panel Appearing in Centre using GridBagLayout" Watch "Panel Appearing in Centre using GridBagLayout" New topic
Author

Panel Appearing in Centre using GridBagLayout

Deirdre Hackett
Greenhorn

Joined: Feb 13, 2008
Posts: 5
Hi,

I'm trying to add panels dynamically to a base panel. I am trying to use GridBagLayout in order to do this.

I would like the first panel that is added to appear in the top left hand side of the frame. However it is appearing half way down the frame.

I'm sorry if this seems to be a very stupid question but am really a beginner have been trying to figure it out for a day. Any help appreciated.

The main class code is below. As is the class AssignmentPanel.

Regards, Deirdre




Michael Dunn
Ranch Hand

Joined: Jun 09, 2003
Posts: 4632
when using GridBagLayout you must read all the documentation, otherwise
you'll find it increasingly frustrating trying to get your GUI correct.

from this link
http://java.sun.com/javase/6/docs/api/java/awt/GridBagLayout.html

you'll find this snippet, which answers your 'centering' question

"GridBagConstraints.weightx, GridBagConstraints.weighty
Used to determine how to distribute space, which is important for specifying
resizing behavior. Unless you specify a weight for at least one component in
a row (weightx) and column (weighty), all the components clump together in the
center of their container. This is because when the weight is zero (the default),
the GridBagLayout object puts any extra space between its grid of cells and the
edges of the container."
Deirdre Hackett
Greenhorn

Joined: Feb 13, 2008
Posts: 5
Thanks Michael for that.
I included the line
gBC.weighty = 1;
but i still don't seeem to be getting what I want. It still places the first placed JPanel in the centre (vertically). I would like the first JPanel to appear in the top left hand corner, without there being anything else placed in the panel.

Or perhaps I am using the wrong Layout manager entirely. Any suggestions on what might work better?
Michael Dunn
Ranch Hand

Joined: Jun 09, 2003
Posts: 4632
> Any suggestions on what might work better?

just going by your
gBC.gridy++;

BoxLayout (Y_AXIS) might be a better LayoutManager
Deirdre Hackett
Greenhorn

Joined: Feb 13, 2008
Posts: 5
Thanks MD for your help but I have now abandoned that approach entirely based on other advice. I am going back to drawing the graphics directly onto a JPanel. Still none the wiser but apparently JPanels aren't the way.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Panel Appearing in Centre using GridBagLayout