使用JButton的Action Listener时出现NullPointerException

时间:2014-03-08 16:23:35

标签: java nullpointerexception jbutton actionlistener

我一直在编写这个程序,出于某种原因,当我尝试使用JButton的Action Listener时,我得到了一个N​​ull指针异常。很抱歉,我的大多数代码都在main方法中,我对面向对象编程的面向对象部分感到很沮丧。问题始于main方法中while(true)语句之后的第一个actionlistener。

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)

2 个答案:

答案 0 :(得分:1)

异常发生在

btnNext.addActionListener(new ActionListener() {

除了btnNext之外,此行可能为空?没有。所以btnNext为空。

事实上,btnNext在执行此代码行时尚未初始化,因为它在SignInFrame的构造函数中初始化,在内部调用

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

正如其名称所示,您传递给invokeLater()的内容将在稍后调用。

坦率地说,你的代码是一团糟。应始终从事件派发线程访问每个Swing组件。因而不是直接在主方法下。这就是在invokeLater调用中初始化帧的原因。

构造函数不应初始化静态字段。按钮应该是框架的私有实例字段。主要方法不应该处理它们。并且有一个无限循环可以将听众添加到按钮中没有任何意义。

阅读Swing教程。

答案 1 :(得分:0)

JButton尚未初始化。您在空白的JButton上调用btnNext.addActionListener。因此,空指针就是这样。

例如:

    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

        }
    });