Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Adding a JLabel to JPanel

Tags:

java

swing

I have simple problem as I am not much familiar with Java GUI. I am trying to make visible the JLable on the below code as I find it hard to understand the concept. But still label is not visible but the frame do open on run time.

public class Sample extends JPanel {

    public void Sample() {
        JPanel p = new JPanel();

        JLabel lab1 = new JLabel("User Name", JLabel.LEFT);
        p.setLayout(new FlowLayout());
        p.add(lab1 = new JLabel("add JLabel"));
    }

    public static void main(String[] args) {

        JFrame frame = new JFrame();
        frame.getContentPane().add(new Sample());

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(200, 200);
        frame.setVisible(true);
    }
}
like image 319
Splitter Avatar asked May 13 '11 05:05

Splitter


2 Answers

You are forgot to add panel p to sample. Either use add(p) at the end or just remove panel p cause your sample class is extending JPanel.

Option 1:

    JPanel p = new JPanel();

    JLabel lab1 = new JLabel("User Name", JLabel.LEFT);
    p.setLayout(new FlowLayout()); 
    p.add(lab1 = new JLabel("add JLabel"));
    add(p);

option 2:

    JLabel lab1 = new JLabel("User Name", JLabel.LEFT);
    setLayout(new FlowLayout()); 
    add(lab1 = new JLabel("add JLabel"));

Also why are you overriding initialization of JLabel? In your code JLable will always hold value "add JLabel". If you want to see "User Name" then use this add(lab1); instead of add(lab1 = new JLabel("add JLabel"));.

May be you just require this:

    JLabel lab1 = new JLabel("User Name", JLabel.LEFT);
    setLayout(new FlowLayout()); 
    add(lab1);

Also constructor can not have return type so remove void from your constructor.

like image 98
Harry Joy Avatar answered Nov 15 '22 06:11

Harry Joy


The constructor that you are using is not a proper constructor .. A java constructor does not have a return type and the void is extra. When in the main method you are calling new Sample() it is not actually calling your method but the default constructor that exists by default.

Try like this ..

public Sample() {
    JPanel p = new JPanel();

    JLabel lab1 = new JLabel("User Name", JLabel.LEFT);
    p.setLayout(new FlowLayout());
    p.add(lab1 = new JLabel("add JLabel"));
}

also you need to do what @Harry Joy suggested to add the add(p); statement otherwise the panel is still not added.

like image 35
aseychell Avatar answered Nov 15 '22 06:11

aseychell