java – What is setBounds and how do I use it?

java – What is setBounds and how do I use it?

You can use setBounds(x, y, width, height) to specify the position and size of a GUI component if you set the layout to null. Then (x, y) is the coordinate of the upper-left corner of that component.

setBounds is used to define the bounding rectangle of a component. This includes its position and size.

The is used in a number of places within the framework.

  • It is used by the layout managers to define the position and size of a component within its parent container.
  • It is used by the paint sub system to define clipping bounds when painting the component.

For the most part, you should never call it. Instead, you should use appropriate layout managers and let them determine the best way to provide information to this method.

java – What is setBounds and how do I use it?

This is a method of the java.awt.Component class. It is used to set the position and size of a component:


public void setBounds(int x,
                  int y,
                  int width,
                  int height) 

Moves and resizes this component. The new location of the top-left corner is specified by x and y, and
the new size is specified by width and height. Parameters:

  • x – the new x-coordinate of this component
  • y – the new y-coordinate of this component
  • width – the new width of this component
  • height – the new height of this component

x and y as above correspond to the upper left corner in most (all?) cases.

It is a shortcut for setLocation and setSize.

This generally only works if the layout/layout manager are non-existent, i.e. null.

Leave a Reply

Your email address will not be published.