Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

How can I place an object in a specific location (x,y) on a JFrame?

like image 809
whiteberryapps Avatar asked Jun 09 '12 16:06

whiteberryapps


2 Answers

Here find the Absolute Positioning Tutorials. Please do read carefully, as to why this approach is discouraged over using LayoutManagers

To add say a 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 example 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

like image 71
nIcE cOw Avatar answered Sep 29 '22 01:09

nIcE cOw


Try these 2... in combination with each other...

setLocation() and setBounds()

Its even better to use GroupLayout, developed by NetBeans team in 2005. WindowsBuilder Pro is a good tool for Building Gui in java

like image 45
Kumar Vivek Mitra Avatar answered Sep 29 '22 00:09

Kumar Vivek Mitra