0

this is my code and when I run this example it gives NullPointerException could you help me please to find the error or why I've got this exception ! my code :

public class Frame extends JFrame
{
    public Frame()
    {
        JLabel label;
        label.setText("test");
        add(label);
        setSize(200,200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }
    public static void main(String[] args) 
    {
        new Frame().setVisible(true);
    }
}

2 Answers2

1

You declare a JLabel variable :

    JLabel label;

And you access it without initializing it first :

    label.setText("test");

You must initialize a variable before accessing it :

    JLabel label = new JLabel ();
    label.setText("test");
Eran
  • 374,785
  • 51
  • 663
  • 734
0

You have not initialized label;

dnsh
  • 3,228
  • 1
  • 18
  • 41