java.lang.NullPointerException in this code

2

This is giving 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; }

}

Class without thread

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)

Class with thread

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)
    
asked by anonymous 09.12.2014 / 11:22

1 answer

3

As you can see in your stack trace :

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

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

In your class PrimosPanel you declare multiple elements but do not initialize them. You should initialize them for example inside the class constructor. Example:

public PrimosPanel() {
    tf1 = new JTextField();
    b1 = new JButton();
    //inicializa todos os elementos
}
    
09.12.2014 / 11:31