Java Reference
In-Depth Information
Components have a 'preferred' size, which depends on the particular object. For example, the preferred
size of a
JButton
object that defines a button is the size that accommodates the label for the button.
Note that you will not normally adjust the size of a component unless you are placing it relative to your
display screen, since the size will be managed automatically when it has a parent component. We will
see the reason for this later in this chapter. A component also has a minimum size and if the space
available to it is less than the minimum size, the component will not be displayed.
The methods to retrieve or alter the size and position are:
Method
Description
void setBounds(int x, int y,
int width,
int height)
Sets the position of the
Component
object to the
coordinates (
x
,
y
), and the width and height of the
object to the values defined by the third and fourth
arguments.
void setBounds(
Rectangle rect)
Sets the position and size of the
Component
object to
be that of the
Rectangle
argument,
rect
.
Rectangle getBounds()
Returns the position and size of the object as an object
of type
Rectangle
.
void
setSize(Dimension
d)
Sets the width and height of the
Component
object to
the values stored in the members of the object
d
.
Dimension
getSize()
Returns the current size of the
Component
object as a
Dimension
object.
setLocation(int x, int y)
Sets the
position of the component to the point
defined by (x, y).
setLocation(Point p)
Sets the position of the component to the point
p.
Point
getLocation()
Returns the position of the
Component
object as an
object of type
Point
.
Another important method defined in the
Component
class is
getToolkit()
. This returns an object
of type
Toolkit
that contains information about the environment in which your application is running,
including the screen size in pixels. You can use the
getToolkit()
method to help set the size and
position of a window on the screen. We can modify the previous example to demonstrate this.
Try It Out
- Sizing Windows with
Toolkit
We'll use the
Toolkit
object to display the window in the center of the screen with the width and
height set as half of the screen width and height:
import javax.swing.JFrame;
import java.awt.Toolkit;
import java.awt.Dimension;
public class TryWindow {