How to Use setBounds() Method in Java
In this tutorial, we are going to see how to use setBounds() method in Java. Layout managers are used to automatically decide the position and size of added components. In the absence of a layout manager, the position and size of the components must be set manually. setBounds() method is used in such a situation to set the position and size. To manually specify the position and size of the components, the layout manager of the frame can be null.
setBounds() Method
setBounds() method needs four arguments. The first two arguments are the x and y coordinates of the upper left corner of the component, the third argument is the width of the component, and the fourth argument is the height of the component.
Syntax
setBounds(int x, int y, int width, int height)
How to Use setBounds() Method in Java
import javax.swing.*; import java.awt.*; public class Main { public static void main(String arg[]) { JFrame f = new JFrame("SetBounds Example"); f.setSize(300, 300); // Set the layout to null f.setLayout(null); // Create button JButton btn = new JButton("Welcome To StackHowTo!"); // Define the position and size of the button btn.setBounds(40,30,200,40); f.add(btn); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setLocationRelativeTo(null); f.setVisible(true); } }
Output: