Use of setBounds Method in Java



The layout managers are used to automatically decide the position and size of the added components. In the absence of a layout manager, the position and size of the components have to be set manually. The setBounds() method in Java is used in such a situation to set the position and size. To specify the position and size of the components manually, the layout manager of the frame can be null.

The setBounds() Method

The setBounds() is a method inherited from Java's AWT (Abstract Window Toolkit) and Swing libraries that enables manual positioning and sizing of GUI components. The setBounds() method needs four arguments. The first two arguments are x and y coordinates, the third argument is the width, and the fourth argument is the height.

Syntax

The following is the syntax:

setBounds(int x-coordinate, int y-coordinate, int width, int height)

Parameters

  • x: Horizontal position from the left border
  • y: Vertical position from the top border
  • width: Width of the component
  • height: Height of the component

Example

Below is an example of setBounds() method in Java:

import javax.swing.*;
import java.awt.*;
public class SetBoundsTest {
   public static void main(String arg[]) {
      JFrame frame = new JFrame("SetBounds Method Test");
      frame.setSize(375, 250);
      // Setting layout as null
      frame.setLayout(null);
      // Creating Button
      JButton button = new JButton("Hello Java");
      // Setting position and size of a button
      button.setBounds(80,30,120,40);
      frame.add(button);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }
}

Output

Comparison Table

The following are some key differences between setBounds() and Layout Manager in Java:

Criteria setBounds() Layout Managers
Positioning Absolute Relative
Resizing Manual Automatic
Maintenance Difficult Easier
Flexibility Low High
Learning Curve Simple Steeper
Alshifa Hasnain
Alshifa Hasnain

Converting Code to Clarity

Updated on: 2025-04-18T17:50:11+05:30

38K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements