Java Swing How to - Set location of JLabel in a JFrame








Question

We would like to know how to set location of JLabel in a JFrame.

Answer

import java.awt.Dimension;
/*from w w  w  .  ja  va2  s  . c  o  m*/
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 panel = (JPanel) frame.getContentPane();
    panel.setLayout(null);

    JLabel label = new JLabel("aaa");
    panel.add(label);
    Dimension size = label.getPreferredSize();
    label.setBounds(100, 100, size.width, size.height);

    frame.setSize(300, 200);
    frame.setVisible(true);

  }
}