Java Swing How to - Place an object in a specific location (x,y) on a JFrame with absolute layout








Question

We would like to know how to place an object in a specific location (x,y) on a JFrame with absolute layout.

Answer

import java.awt.Color;
/*from  ww  w. j a  v a  2 s  . com*/
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Main {

  public static void main(String... args) {
    JFrame frame = new JFrame();
    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);
  }
}