java.lang.Nullpointerexception in this code

Asked

Viewed 527 times

2

This gives java.lang.Nullpointerexception error in these two classes.

import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class PrimosPanel extends JPanel { 
    private JTextField tf1, tf2;
    private JButton b1, b2, b3;
    private JTextArea ta1;
    public PrimosPanel() { }
    public JButton getButton1() { return b1; }
    public JButton getButton2() { return b2; }
    public JButton getButton3() { return b3; }
    public JTextArea getTextArea() { return ta1; }
    public JTextField getTextField1(){ return tf1; }
    public JTextField getTextField2(){ return tf2; }

}

Threadless class

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;


public class PrimosST extends JFrame implements ActionListener {

    private PrimosPanel pp; //componente de interface
    private boolean stop; //variável de contole de processamento
    public PrimosST() {
        super("Primos sem Thread");
        setContentPane(pp = new PrimosPanel());
        pp.getButton1().addActionListener(this);
        pp.getButton2().addActionListener(this);
        pp.getButton3().addActionListener(this);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(300, 150);  
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getSource()==pp.getButton3()) {
            try {
                pp.getButton2().setEnabled(false);
                pp.getButton3().setEnabled(false);
                calcPrimos(Integer.parseInt(pp.getTextField1().getText()),
                           Integer.parseInt(pp.getTextField2().getText()));
                pp.getButton2().setEnabled(true);
                pp.getButton3().setEnabled(true);


            } catch (NumberFormatException nfe) {
                pp.getTextArea().setText("Intervalo invalido!");
                return;

            }
        } else if(e.getSource()==pp.getButton2()) {
            pp.getTextArea().setText(null);

        } else {
           stop = true;
            pp.getButton2().setEnabled(true);
            pp.getButton3().setEnabled(true);
        }
    }

    private void calcPrimos(int inicio, int fim) {
        pp.getTextArea().setText("Calculando:\n");
        stop = false;
        for(int n = inicio; n<=fim && !stop; n++) {
            int i;
            for(i=2; i<=n; i++)
                if(n%i==0) break;
            if(i==n) pp.getTextArea().append(n + ",");
            }

        pp.getTextArea().append("\n");
        }
    public static void main(String[] args) {
     new PrimosST().setVisible(true);
    }
}

Error Exception in thread "main" java.lang.NullPointerException

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at PrimosCT.<init>(PrimosCT.java:16)
    at PrimosCT$2.run(PrimosCT.java:71)
    at java.awt.event.InvocationEvent.dispatch(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$400(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)

Thread class

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class PrimosCT extends JFrame implements ActionListener {

    private PrimosPanel pp;
    private boolean stop;
    public PrimosCT() {
        super("Primos com  Thread");
        setContentPane(pp = new PrimosPanel());
        pp.getButton1().addActionListener(this);
        pp.getButton2().addActionListener(this);
        pp.getButton3().addActionListener(this);
        setSize(300, 150);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e ) { stop = true; }

        } );
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getSource()==pp.getButton3()) {
            try {
                pp.getButton2().setEnabled(false);
                pp.getButton3().setEnabled(false);
                new Calculo().start();

            } catch(NumberFormatException nfe) {
                pp.getTextArea().setText("Intervalo invalido!");
                return;
            }   
        } else if(e.getSource()==pp.getButton2()) {
            pp.getTextArea().setText(null);
        } else {
            stop = true;
            pp.getButton2().setEnabled(true);
            pp.getButton3().setEnabled(true);

        }
    }
 public void calcPrimos(int inicio, int fim) {
 pp.getTextArea().setText("Calculando:\n");
 stop = false;
 for(int n= inicio; n<= fim && !stop; n++) {
     int i;
     for(i=2; i<n; i++)
         if(n%i==0) break;
     if(i==n)pp.getTextArea().append(n + ", ");

  }
 pp.getTextArea().append("\n");
 }
 private class Calculo  extends Thread { //clase interna
     @Override
     public void run() { //adiciona cálculo
         calcPrimos(Integer.parseInt(pp.getTextField1().getText()),
                   Integer.parseInt(pp.getTextField2().getText()));
         pp.getButton2().setEnabled(true);


     } 
 }
public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            new PrimosCT().setVisible(true);
        }
    } );
}
}

Error: Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at PrimosCT.<init>(PrimosCT.java:16)
    at PrimosCT$2.run(PrimosCT.java:71)
    at java.awt.event.InvocationEvent.dispatch(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$400(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)

1 answer

3


As you can see in your stack trace:

at PrimosCT.<init>(PrimosCT.java:16)

the exception occurs on line 16 of its class PrimosCT, which is the line pp.getButton1().addActionListener(this);. The exception is made because the getButton1() is returning null.

In his class PrimosPanel you declare several elements but do not initialize them. You should initialize them for example within the class constructor. Example:

public PrimosPanel() {
    tf1 = new JTextField();
    b1 = new JButton();
    //inicializa todos os elementos
}
  • Still giving build error.

  • @Leonardooliveira but the stack trace changed? Until then it was possible to identify a problem, the NPE, maybe have more.

  • @Leonardooliveira put his code to run and it was normal, initiating all components within the constructor, so there is no more error in the compilation. But the program itself does nothing, there may be logic errors in it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.