Spacing and Aligning Components

     

Spacing and Aligning Components

Spacers

There is a class that inherits from JComponent called Box. This is a lightweight class that uses BoxLayout as its Layout Manager. You can use this class to get at the convenience methods it makes available. These methods allow you to add invisible components to the layout that help you fit, position, and size the regions of your layout. Specifically, they help you do that by creating certain relationships between your visible control components.

We won't go into them in much depth. Suffice to say, here they are, here is what they're for, and go try them out for yourself to get the feel for them. This is the point in Swing programming that it becomes a little like learning to drive: eventually, you just need to feel when to shift gears and how quickly to let up on the clutch.

Glue

Glue represents space of malleable size in a layout. Adding glue between two components tells the runtime to take excess space in the layout and smoosh it between the components.

 

 container.add(buttonOne); container.add(Box.createHorizontalGlue()); container.add(buttonTwo); 

You can also createVerticalGlue();.

Area

A rigid area is an invisible region that is always of the specified size. You use it to create a certain amount of space between two components that you don't want to change, or perhaps to push text up toward the top of your window by placing a rigid area below it.

An example follows :

 

 static Component Box.createRigidArea(Dimension d) 

Dimension takes two int s specifying the height and width.

 

 container.add(buttonOne); container.add(Box.createRigidArea(new Dimension(10,0))); container.add(buttonTwo); 

Strut

A strut is an invisible component of fixed length. It is used to force space between two components. The strut has no width at all, except there is excess space surrounding it, in which case it will fill up the space in the manner of any component. There are two kinds of struts: vertical and horizontal.

Create a strut using these methods:

 

 static Component createVerticalStrut(int height) static Component createHorizontalStrut(int width) 

Here is an example of how to use a strut to put space between two buttons :

 

 container.add(buttonOne); container.add(Box.createVeticalStrut(15)); container.add(buttonTwo); 

You'll notice in this case, the strut acts like the rigid area. However, it is recommended that you use rigid areas instead of struts, because struts can have unlimited length, which could cause undesirable results in nested components.



Java Garage
Java Garage
ISBN: 0321246233
EAN: 2147483647
Year: 2006
Pages: 228
Authors: Eben Hewitt

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net