A Beginner's Guide to Java Swing

This is an pretty old post from my blog, which has been preserved in case its content is of any interest. You might want to go back to the homepage to see some more recent stuff.

For those looking for a quick introduction to laying out Graphical User Interface components using Java’s Swing technology, this guide may prove helpful. (But probably not.)

Swing Components all have a few common properties that affect how they are laid out on the GUI. These are:

Swing components are arranged inside their parent panels by Layout Managers. Many layout managers are available to achieve certain common layouts. They include:

I hope that helps.

Comments

BoxLayout is my go-to for swing. Don't touch the others with a barge pole, unless you want something really simple, then go for FlowLayout until it breaks.

A lot of them seem to assume that they can ask for a size up front and then not recalibrate if you grow the size of a component later.
Also, see Box.createHorizontalGlue() and Box.createVerticalGlue() to make BoxLayout sit down and shut up

Whoa, how did I go this far without knowing about the Box class? That looks really handy!

GridBagLayout is my bitch. I used to do things with that class that would make the Mask of Winters weep with the confusion and horror of it all.

But yes, really, download http://www.miglayout.com/ and never look back.

Eldritchreality 03 March 2012

Arigato yo!

I'm sure I'll find this very useful when I'm sober in the morning.

It is unsurprisingly javaified. First you must appease the machine spirit with the invocaition "Public Static Void Main!"

I suppose it could be worse, I could be trying to do layout in css. Who the fuck though floats were a sensible way to implement a proper design grid?

MiG Layout does look handy, and would save the possible pain of porting the whole thing to SWT.

CSS is also similar levels of evil, I could quite happily do a companion post to this about the madness of laying out components on websites :)

Add a Comment