How do I place swing component using absolute coordinates?

In this example you can see how we do an absolute positioning to a swing component in the content panel. In this example we use a JPanel as the container and we didn’t set a layout manager into it.

To position the component on the container we use the setBounds() method of the component. This method takes the x and y coordinate position and also the width and height of the component.

package org.kodejava.example.swing;

import javax.swing.*;

public class AbsolutePositionDemo extends JFrame {
    public AbsolutePositionDemo() {
        initializeUI();
    }

    private void initializeUI() {
        setSize(400, 400);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        JPanel panel = new JPanel(null);

        JTextField textField = new JTextField(20);
        textField.setBounds(50, 50, 100, 20);

        JButton button = new JButton("Button");
        button.setBounds(200, 100, 100, 20);

        JCheckBox checkBox = new JCheckBox("Check Me!");
        checkBox.setBounds(300, 250, 100, 20);

        panel.add(textField);
        panel.add(button);
        panel.add(checkBox);

        setContentPane(panel);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new AbsolutePositionDemo().setVisible(true);
            }
        });
    }
}

Wayan Saryada

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. You can support my works by donating here. Thank you 🙂.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.