How to place an object in a specific place (x, y) on a JFrame?

How to place an object in a specific place (x, y) on a JFrame?

+5
source share
4 answers

Here you will find absolute positioning tutorials . Please read carefully why this approach is not recommended with LayoutManagers.

To add JButton to your JPanel, you can use this:

JButton button = new JButton("Click Me");
button.setBounds(5, 5, 50, 30);
panel.add(button);

Here try this sample program:

import java.awt.*;
import javax.swing.*;

public class AbsoluteLayoutExample
{
    private void displayGUI()
    {
        JFrame frame = new JFrame("Absolute Layout Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel contentPane = new JPanel();
        contentPane.setOpaque(true);
        contentPane.setBackground(Color.WHITE);
        contentPane.setLayout(null);

        JLabel label = new JLabel(
            "This JPanel uses Absolute Positioning"
                                    , JLabel.CENTER);
        label.setSize(300, 30);
        label.setLocation(5, 5);

        JButton button = new JButton("USELESS");
        button.setSize(100, 30);
        button.setLocation(95, 45);

        contentPane.add(label);
        contentPane.add(button);

        frame.setContentPane(contentPane);
        frame.setSize(310, 125);
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String... args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                new AbsoluteLayoutExample().displayGUI();
            }
        });
    }
}

Absolute Positioning Output

+9
source

Try these 2 ... combined with each other ...

setLocation() and setBounds()

Better yet, use GroupLayout, developed by the NetBeans team in 2005. WindowsBuilder Pro is a good tool for creating Gui in java

+3
source

, :

setLayout(null); 

:

setLocation(x,y);
+2

All Articles