Wednesday, June 6, 2007

JCOMPONENT SIZING AND POSITIONING METHODS.

JCOMPONENT SIZING AND POSITIONING METHODS.

Since JComponent extends java.awt.container, it inherits the sizing and positioning functionality of the AWT (for those familiar with AWT).

To manage a component's preferred, minimum and maximum size, the following methods are used:

the setters: setPreferred size(), setMinimumSize(), setMaximumsize().
The getters: getPreferredSize(), getMinimumSize(), getMaximumSize().

All these methods return a Dimension instance. Note that the size of components in a container is layout manager specific (the layout manager is the class responsible for laying out the components of a a container. ) The layout manager might ignore or respect sizing commands.

To assign a component both a size and a position with its parent container, we use JComponent's setBounds() method. The method takes a rectangle parameter or 4 int parameters that represent the x-coordinate, y-coordinate, width and height. Note that layout managers always have the first crack at component sizing, so setBounds() might be ignored in some cases. Use setBounds though if your component has no layout manager.

You can query a component's size using its getHeight() and getWidth() methods.

Also we can set a component's position within its container using the setLocation(int x, int y) method.

JComponent also maintains an alignment. Horizontal and vertical alignment can be specified by float values between 0.0 and 1.0. 0.5 means center, close to 0.0 means left or top and closer to 1.0 means right or bottom. The JComponent methods are : setAlignmentX(float f), setAlignmentY(float f).

No comments: