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
  • 387,369
  • 54
  • 702
  • 768
0

You have not initialized label;

dnsh
  • 3,516
  • 2
  • 22
  • 47