jQuery in Action, 3rd edition
The moose likes Swing / AWT / SWT and the fly likes aligning label and fields in Swing Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "aligning label and fields in Swing" Watch "aligning label and fields in Swing" New topic

aligning label and fields in Swing

choubix alex

Joined: Dec 25, 2009
Posts: 22

I am creating a login screen to get up to speed with Swing.
When I run the following code all the elements are displayed BUT their position on the screen is not correct.
is it possible to display the elements like this

username: (textfield here)
password: (passwordfield here)
comment: (comment field here)


while aligning them so it looks nice? (all the labels / fields aligned)

thank you for your time

ps: please feel free to comment my code on my code as this is new for me and that I would like to progress fast


Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 10815

What you need is LayoutManagers.
Recommended reading: http://java.sun.com/docs/books/tutorial/uiswing/layout/using.html
Also google for MigLayout Some people feel it is easier to use than GridBagLayout

Since you are starting to learn, I strongly recommend, do not use drag and drop style tools. Hand coding has numerous advantages. Search the forums for details on this topic. It has been discussed many times before.

[How to ask questions] [Donate a pint, save a life!] [Onff-turn it on!]
choubix alex

Joined: Dec 25, 2009
Posts: 22
Thanks again!

I've stumble on MiG shortly after posting my message and I have managed to position my labels in a much better way.
I was tempted to use a Visual builder (netbeans provides one I think) but I have decided to start coding my UI instead so that I can learn better/more.

Mayur Gosalia
Ranch Hand

Joined: Jan 03, 2010
Posts: 54
use grid layout with gridbag constraints..that way you have alot more control over your placements in the panel.
Rob Spoor

Joined: Oct 27, 2005
Posts: 20269

Mayur Gosalia wrote:use grid layout with gridbag constraints..

Don't you mean GridBagLayout, instead of GridLayout? Because GridLayout doesn't use any constraints, it just uses the largest width and height for all components.

How To Ask Questions How To Answer Questions
I agree. Here's the link: http://aspose.com/file-tools
subject: aligning label and fields in Swing
It's not a secret anymore!