Unable to solve Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException

1.4k Views Asked by At

I am currently creating a payroll software and the RemoveEmployee class does not function due to an error. I tried working my way backwards to resolve the issue but I was unable to due to my lack of experience in java.

package Assigment;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author dj_sp
 */
public class RemoveEmployee extends javax.swing.JFrame {
File sallaried=new File("Salaried Employee Registration.txt");  
File hourly=new File("Hourly Employee Registration.txt");
File commission=new File("Commission Employee Registration.txt");
//creating  a text files

    /**
     * Creates new form RemoveEmployee
     */
    public RemoveEmployee() {
       initComponents();
       removeSalEmp();                             
       removeHourlyEmp();
       removeCommissionEmp();
        //calling methods
       }

    public void removeSemp(){

       }
       public void removeSalEmp(){
        DefaultTableModel model=(DefaultTableModel)tblSalaried.getModel();

        FileReader fr;
        try {
            fr = new FileReader(sallaried);
            BufferedReader br=new BufferedReader(fr);                               
                 //reading from text file
             String line;
             int column;
             int row=0;

        while(( line=br.readLine())!=null){
   tblSalaried.setValueAt(line,row,0);
   tblSalaried.setValueAt(br.readLine(),row,1);
   tblSalaried.setValueAt(br.readLine(),row,2);
   tblSalaried.setValueAt(br.readLine(),row,3);
   tblSalaried.setValueAt(br.readLine(),row,4);
   tblSalaried.setValueAt(br.readLine(),row,5);
   tblSalaried.setValueAt(br.readLine(),row,6);                                     
   tblSalaried.setValueAt(br.readLine(),row,7);
   tblSalaried.setValueAt(br.readLine(),row,8);
   tblSalaried.setValueAt(br.readLine(),row,9);

            row++;
             //sets to a jtable
}


            br.close();
            fr.close();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(RemoveEmployee.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(RemoveEmployee.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

       public void removeHourlyEmp(){
DefaultTableModel table =(DefaultTableModel)tblSalaried.getModel();

        FileReader fr;
        try {
            fr = new FileReader(hourly);
            BufferedReader br=new BufferedReader(fr);

             String line;
             int column;
             int row=0;

        while(( line=br.readLine())!=null){
   tblHourly.setValueAt(line,row,0);
   tblHourly.setValueAt(br.readLine(),row,1);
   tblHourly.setValueAt(br.readLine(),row,2);
   tblHourly.setValueAt(br.readLine(),row,3);
   tblHourly.setValueAt(br.readLine(),row,4);
   tblHourly.setValueAt(br.readLine(),row,5);
   tblHourly.setValueAt(br.readLine(),row,6);
   tblHourly.setValueAt(br.readLine(),row,7);
   tblHourly.setValueAt(br.readLine(),row,8);



            row++;

}


            br.close();
            fr.close();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(RemoveEmployee.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(RemoveEmployee.class.getName()).log(Level.SEVERE, null, ex);
        }
       }


    public void removeCommissionEmp(){
           DefaultTableModel model=(DefaultTableModel)tblCommission.getModel();

        FileReader fr;
        try {
            fr = new FileReader(commission);
            BufferedReader br=new BufferedReader(fr);

             String line;
             int column;
             int row=0;

        while(( line=br.readLine())!=null){
   tblCommission.setValueAt(line,row,0);
   tblCommission.setValueAt(br.readLine(),row,1);
   tblCommission.setValueAt(br.readLine(),row,2);
   tblCommission.setValueAt(br.readLine(),row,3);
   tblCommission.setValueAt(br.readLine(),row,4);
   tblCommission.setValueAt(br.readLine(),row,5);
   tblCommission.setValueAt(br.readLine(),row,6);
   tblCommission.setValueAt(br.readLine(),row,7);
   tblCommission.setValueAt(br.readLine(),row,8);
   tblCommission.setValueAt(br.readLine(),row,9);


            row++;

}


            br.close();
            fr.close();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(RemoveEmployee.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(RemoveEmployee.class.getName()).log(Level.SEVERE, null, ex);
        }
       }
/**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content ofs("unchecked")
     *  */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>                        


    // Variables declaration - do not modify                     
    // End of variables declaration                   

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         



        DefaultTableModel model=(DefaultTableModel)tblSalaried.getModel();
        int selectedRow=tblSalaried.getSelectedRow();

        int dialogResult = JOptionPane.showConfirmDialog(null,"Would you like to remove selected employee");
        //displays confirmation dialog to user
    if(dialogResult == JOptionPane.YES_OPTION){
         model.removeRow(selectedRow);
        //gets the user answer and if true removes employee from table


         String newwFile = "Salaried Employee Registration2.txt";
         //creating new text file
        File newFile = new File(newwFile);
        try {
            FileWriter fw = new FileWriter(newFile);
            BufferedWriter bw = new BufferedWriter(fw);
            int rowCount=tblSalaried.getRowCount();
            for(int i = 0; i < tblSalaried.getRowCount(); i++){//rows
                for(int j = 0; j < tblSalaried.getColumnCount(); j++){//columns
                  //

                   if(tblSalaried.getValueAt(i,j)!=null){
                    bw.write((String) tblSalaried.getValueAt(i,j));
                    bw.newLine();
                   }
                    //writing to a file while jtable is nt equal to nothing
                }


            }
            JOptionPane.showMessageDialog(null, "Employee has been removed from the system");
            //display a message to user 
            bw.close();
            fw.close();

            sallaried.delete();
            newFile.renameTo(sallaried);
            //deletes old file,
            // renames new file to the old file



        } catch (IOException ex) {
            Logger.getLogger(RemoveEmployee.class.getName()).log(Level.SEVERE, null, ex);
        }

    }else
    {

    }



    }                                        

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        MainMenu FirstMenu=new MainMenu();
        MainMenu.setVisible(true);
        this.setVisible(false);
    }                                        

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
         DefaultTableModel model=(DefaultTableModel)tblHourly.getModel();
        int selectedRow=tblHourly.getSelectedRow();

          int dialogResult = JOptionPane.showConfirmDialog(null,"Would you like to remove selected employee");
          if(dialogResult == JOptionPane.YES_OPTION){
               model.removeRow(selectedRow);


         String newwFile = "Hourly Employee Registration2.txt";
        File newFile = new File(newwFile);
        try {
            FileWriter fw = new FileWriter(newFile);
            BufferedWriter bw = new BufferedWriter(fw);
            int rowCount=tblHourly.getRowCount();
            for(int i = 0; i < tblHourly.getRowCount(); i++){//rows
                for(int j = 0; j < tblHourly.getColumnCount(); j++){//columns


                   if(tblHourly.getValueAt(i,j)!=null){
                    bw.write((String) tblHourly.getValueAt(i,j));
                    bw.newLine();
                   }

                }


            }
              JOptionPane.showMessageDialog(null, "Employee has been removed from the system");

            bw.close();
            fw.close();

            hourly.delete();
            newFile.renameTo(hourly);



        } catch (IOException ex) {
            Logger.getLogger(RemoveEmployee.class.getName()).log(Level.SEVERE, null, ex);
        }
          }

    }                                        

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        DefaultTableModel model=(DefaultTableModel)tblCommission.getModel();
        int selectedRow=tblCommission.getSelectedRow();

        int dialogResult = JOptionPane.showConfirmDialog(null,"Would you like to remove selected employee");
          if(dialogResult == JOptionPane.YES_OPTION){
                model.removeRow(selectedRow);


         String newwFile = "Commission Employee Registration2.txt";
        File newFile = new File(newwFile);
        try {
            FileWriter fw = new FileWriter(newFile);
            BufferedWriter bw = new BufferedWriter(fw);
            int rowCount=tblCommission.getRowCount();
            for(int i = 0; i < tblCommission.getRowCount(); i++){//rows
                for(int j = 0; j < tblCommission.getColumnCount(); j++){//columns


                   if(tblCommission.getValueAt(i,j)!=null){
                    bw.write((String) tblCommission.getValueAt(i,j));
                    bw.newLine();
                   }

                }


            }
            JOptionPane.showMessageDialog(null, "Employee has been removed from the system");

            bw.close();
            fw.close();

            commission.delete();
            newFile.renameTo(commission);




        } catch (IOException ex) {
            Logger.getLogger(RemoveEmployee.class.getName()).log(Level.SEVERE, null, ex);
        }
          }

    }                                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(RemoveEmployee.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(RemoveEmployee.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(RemoveEmployee.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(RemoveEmployee.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new RemoveEmployee().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JSeparator jSeparator3;
    private javax.swing.JTable tblCommission;
    private javax.swing.JTable tblHourly;
    private javax.swing.JTable tblSalaried;
    // End of variables declaration                   
}

The error message I am receiving. All of my other classes are functioning except this one. I tried re-initialising the constructors but nothing helped.

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at Assigment.RemoveEmployee.removeSalEmp(RemoveEmployee.java:47)
    at Assigment.RemoveEmployee.<init>(RemoveEmployee.java:37)
    at Assigment.RemoveEmployee$1.run(RemoveEmployee.java:376)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
1

There are 1 best solutions below

0
On

In the code you posted, I don't see where you assign a value to tblSalaried. It is a member of class RemoveEmployee. Unless you assign it a value, it is null. Hence when you try to access it, you get NullPointerException. And according to the code you posted, as well as the stack trace you posted, the NullPointerException is being thrown from this line (in method removeSalEmp()):

DefaultTableModel model=(DefaultTableModel)tblSalaried.getModel();

This would be line 47 in file RemoveEmployee.java, as stated in the stack trace you posted.

I suggest that in your initComponents() method you initialize class members, like tblSalaried. You need to add something like the following:

tblSalaried = new JTable();

For your information, I see some other problems with your code, but I think it is better that you first discover them by yourself. You can always post another question :-)