How to Change the Position of JButton in Java
In this tutorial, we are going to see how to change the position of JButton 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 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()
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)
Java Program to Change the Position of JButton:
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: