Question

I've been making this program and for some reason I get a Null Pointer Exception when I try to use an Action Listener for a JButton. Sorry that most of my code is in the main method, I kind of suck at the object oriented part of object oriented programming.The problem starts at the first actionlistener after the while(true) statement in the main method.

public class SignInFrame extends JFrame  {

/**
 * 
 */
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private static JTextField input;
private static JButton btnNext;
private static JButton btnYes;
private static JButton btnNo;
private static JLabel output;
private static String idstring;
private static int yesno = 0;
private static int id = 0;
/**
 * Launch the application.
 */
public static int getIndex(int[] array, int x){
    int index = -1;
    for(int i = 0; i < array.length; i++){
      if(array[i] == x)
        index = i;
    }
    return index;
  }

public static void main(String[] args) throws Exception {

    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                SignInFrame frame = new SignInFrame();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

    int i;
    DateFormat dateFormat = new SimpleDateFormat("MM_dd_yyyy");
    Date date = new Date();
    File file = new File("Attendance/" + (dateFormat.format(date) + "_Attendance.txt"));
    File numfile = new File("DataBase/Student Number DataBase.txt");
    File namfile = new File("DataBase/Student Name DataBase.txt");
    file.getParentFile().mkdirs();
    PrintWriter info = new PrintWriter(file);
    PrintWriter numdata = new PrintWriter(new FileWriter(numfile,true));
    PrintWriter namdata = new PrintWriter(new FileWriter(namfile,true));

    @SuppressWarnings("resource")
    Scanner sc = new Scanner(namfile);
    List<String> lines = new ArrayList<String>();
    while (sc.hasNextLine()) {
      lines.add(sc.nextLine());
    }
    String[] namedatabase = lines.toArray(new String[150]);

    @SuppressWarnings("resource")
    Scanner scc = new Scanner(numfile);
    List<Integer> numbers = new ArrayList<Integer>();
    while (scc.hasNextInt()) {
      numbers.add(scc.nextInt());
    }
    int[] numberdatabase = new int[150];
    for(int p=0, len = numbers.size(); p < len; p++){
    numberdatabase[p] = numbers.get(p);
    }

    while(true){

          btnNext.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    idstring = input.getText();
                    id = Integer.parseInt(input.getText());
                }
            });      
          if(idstring == "000") break;
          while(idstring.length() != 9){
            output.setText("Error(not 9-digits), retype it");
            btnNext.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    idstring = input.getText();
                    id = Integer.parseInt(input.getText());
                }
            });
          }
          while(getIndex(numberdatabase, id) == -1){
            output.setText("Is your Employee Number " + id + "?");
            btnNext.setVisible(false); 
            btnYes.setVisible(true); 
            btnNo.setVisible(true);

            btnYes.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                     yesno = 1;
                }
            });
            btnNo.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    yesno = 2;                  }
            });


            if(yesno == 1){     
              for(i = 0; i < numberdatabase.length; i++){
                if(numberdatabase[i] == 0) break;
              }
              numberdatabase[i] = id;
              numdata.println(id);
              output.setText("Write your FIRST AND LAST name: ");
              btnNext.setVisible(true); 
              btnYes.setVisible(false); 
              btnNo.setVisible(false);
              namedatabase[i] = input.getText();
              namdata.println(namedatabase[i]);
            }
            if(yesno == 2){
              output.setText("Retype your Employee ID: ");
              btnNext.setVisible(true); 
              btnYes.setVisible(false); 
              btnNo.setVisible(false);
              btnNext.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        idstring = input.getText();
                        id = Integer.parseInt(input.getText());
                    }
                });               
              while(idstring.length() != 9){
                output.setText("Error(not 9-digits), retype it: ");
                btnNext.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        idstring = input.getText();
                        id = Integer.parseInt(input.getText());
                    }
                });
              }
            }
          }

          DateFormat timeFormat = new SimpleDateFormat("hh:mm a");
          Date time = new Date();
          System.out.println("");
          System.out.println("You logged in at " + timeFormat.format(time) + " as " + namedatabase[getIndex(numberdatabase, id)] + " : " + id); 
          info.print("Employee ID: " + id);
          info.print("  Name: " + namedatabase[getIndex(numberdatabase, id)]);
          info.println("  " + timeFormat.format(time));
        }

    info.close();
    numdata.close();
    namdata.close();    
}

/**
 * Create the frame.
 */
public SignInFrame() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 450, 300);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    JLabel attendance = new JLabel("Attendance");
    attendance.setBounds(5, 5, 424, 25);
    attendance.setFont(new Font("Tahoma", Font.BOLD, 20));
    attendance.setHorizontalAlignment(SwingConstants.CENTER);
    contentPane.add(attendance);

    output = new JLabel("Write your 9-digit Employee ID");
    output.setHorizontalAlignment(SwingConstants.CENTER); 
    output.setBounds(84, 73, 271, 14);
    contentPane.add(output);

    input = new JTextField();
    input.setBounds(176, 98, 86, 20);
    contentPane.add(input);
    input.setColumns(10);

    btnNext = new JButton("Next");
    btnNext.setBounds(173, 129, 89, 23);
    contentPane.add(btnNext);

    btnYes = new JButton("Yes");
    btnYes.setVisible(false); 
    btnYes.setBounds(123, 129, 89, 23);
    contentPane.add(btnYes);

    btnNo = new JButton("No");
    btnNo.setVisible(false); 
    btnNo.setBounds(225, 129, 89, 23);
    contentPane.add(btnNo);
   }
   }

exception trace
    java.lang.NullPointerException
    at SignInFrame.main(SignInFrame.java:94)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at      edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
Was it helpful?

Solution

The exception happens at the line

btnNext.addActionListener(new ActionListener() {

What could be null at this line except btnNext? Nothing. So btnNext is null.

And indeed, btnNext is not initialized yet when this line of code is executed, since it's initialized in the constructor of SignInFrame, which is called inside

EventQueue.invokeLater(new Runnable() {
    public void run() {
        try {
            SignInFrame frame = new SignInFrame();
            frame.setVisible(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
});

As its name indicates, what you pass to invokeLater() will be invoked... later.

Your code, quite frankly, is a mess. Every Swing component should always be accessed from the event dispatch thread. And thus not directly under the main method. That's why the frame is initialized inside the invokeLater call.

A constructor shouldn't initialize a static field. The buttons should be private instance fields of your frame. And the main method shouldn't deal with them. And having an infinite loop which adds listeners to buttons doesn't make any sense.

Read the Swing tutorial.

OTHER TIPS

The JButton hasn't been initialized yet. Your calling btnNext.addActionListener on a blank JButton. The null pointer is because of that.

For example:

    JButton btnNewButton_1 = new JButton("New");

    btnNewButton_1.setBackground(Color.LIGHT_GRAY);
    btnNewButton_1.setBounds(236, 228, 89, 23);
    frame.getContentPane().add(btnNewButton_1);
    btnNewButton_1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            //actions here

        }
    });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top