javanullpointerexception

Why am I getting a NullPointerException and no display the component i added?


Below, you will find the error message I received. The output show only the JFrame with no content.

Exception in thread "main" java.lang.NullPointerException
  at java.awt.Container.addImpl(Container.java:1043)
  at java.awt.Container.add(Container.java:363)
  at gui.<init>(gui.java:37)
  at gui.main(gui.java:15)
Java Result: 1

Code follows:

import javax.swing.*;
import java.awt.*;

public class gui extends JFrame {
    JPanel p1;
    JTextField tf1,tf2,tf3,tf4;
    JLabel lbl1,lbl2,lbl3,lbl5,lbl6,lbl7,lbl8,lbl9,lbl10;
    JTextArea txtMessage;
    JButton b1,b2,b3,b4,b5;

    public static void main(String [] args) {
        gui f = new gui();
        f.setTitle("RSA.");
        f.setVisible(true);
        f.setSize(700,500);
      
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public gui() {
        lbl1 = new JLabel("Enter first prime number : ");
        lbl2 = new JLabel("Enter second prime number: ");
        lbl2 = new JLabel("Enter the message to be send : ");
        tf1 = new JTextField(15);
        tf2 = new JTextField(15);
        txtMessage = new JTextArea("Please enter",5,20);
        p1 = new JPanel();
        p1.add(lbl1);
        p1.add(tf1);
        p1.add(lbl2);
        p1.add(tf2);
        p1.add(lbl3);
        p1.add(txtMessage);
    }
}

I will appreciate for those who give the solution to me.Thanks


Solution

  • You need to add this line in the constructor:

    this.add(p1);