Not able to set location of JLabel on a JPanel

John Watson picture John Watson · Feb 22, 2012 · Viewed 34.1k times · Source

I have set location (0,0) for the JLabel with respect to the JPanel. But it is appering at the center and top. What mistake am I making ?

import java.awt.*; 
import javax.swing.*; 
import java.awt.event.*;
public class Main extends JFrame 
{ 
private JPanel panel;
private JLabel label1;
public Main() 
{ 
    panel = new JPanel(); 
    panel.setBackground(Color.YELLOW); 

    ImageIcon icon1 = new ImageIcon("3.png"); 
    label1 = new JLabel(icon1); 
    label1.setLocation(0,0); 
    panel.add(label1);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.getContentPane().add(panel); 
    this.setSize(500,500); 
    this.setVisible(true); 

} 

public static void main (String[] args) {
    new Main(); 
} 
} 

Answer

GambitGeoff picture GambitGeoff · Feb 22, 2012

Setting the layout manager to null didn't work for me. Try this:

// setLocation(0,0); //remove line.
panel.setLayout(new FlowLayout(FlowLayout.LEFT)); // change from 'centered'

Voila! :) I recommend you look into the new RelativeLayout manager.