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);
}
}
You are forgot to add panel
pto sample. Either useadd(p)at the end or just remove panelpcause your sample class is extending JPanel.Option 1:
option 2:
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 ofadd(lab1 = new JLabel("add JLabel"));.May be you just require this:
Also constructor can not have return type so remove void from your constructor.