
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 |