Java Swing GUI

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() 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.

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
      // Create button
      JButton btn = new JButton("Welcome To StackHowTo!");
      // Define the position and size of the button


mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *