Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not able to set location of JLabel on a JPanel

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(); 
} 
} 
like image 649
John Watson Avatar asked Feb 22 '12 12:02

John Watson


Video Answer


1 Answers

Use Layouts!

Screenshot of left aligned image icon

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.net.URL;

public class Main extends JFrame
{
    private JPanel panel;
    private JLabel label1;

    public Main() throws Exception
    {
        // Do use layouts (with padding & borders where needed)!
        panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        panel.setBackground(Color.YELLOW);

        URL url = new URL("http://pscode.org/media/starzoom-thumb.gif");
        ImageIcon icon1 = new ImageIcon(url);

        label1 = new JLabel(icon1);
        // Don't use null layouts, setLocation or setBounds!
        //label1.setLocation(0,0);
        panel.add(label1);
        pack();
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        getContentPane().add(panel);
        setSize(400,200);
        setLocationByPlatform(true);
        setVisible(true);
    }

    public static void main (String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                try {
                    new Main();
                } catch(Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

Update

There seems to be a lot of confusion amongst replies to this thread, so to clarify one matter:

  • A JPanel does have a FlowLayout by default.
  • The FlowLayout it gets, comes from the 'no args' constructor, e.g. new FlowLayout()1.
  • The no-args constructor for a FlowLayout produces..

    (1) ..a new FlowLayout with a centered alignment and a default 5-unit horizontal and vertical gap.

like image 166
Andrew Thompson Avatar answered Oct 21 '22 05:10

Andrew Thompson