为什么这个Java程序会抛出NullPointerException?

时间:2013-04-30 22:34:13

标签: java swing user-interface nullpointerexception

在这个程序中,我需要我的程序将类的状态放入一个不可编辑的JTextArea中,但我一直得到一个NullPointerException。我有一种感觉,这与每次启动时对象被反序列化的事实有关。如果我删除它并用实际的String替换它,它工作正常。我该怎么办?我将在下面发布两个课程。

BankGUI课程:

package GUIs;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridBagLayout;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ListSelectionModel;
import javax.swing.ScrollPaneConstants;
import javax.swing.UIManager;

public class BankGUI {

    BankAccount account;

    private void deserializeAccount() {
        try {
            ObjectInputStream objectStream2 = new ObjectInputStream(
                    new FileInputStream("bankAccounts.txt"));
            account = (BankAccount) objectStream2.readObject();
            objectStream2.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        System.out.println("");
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            e.printStackTrace();
        }
        BankGUI gui = new BankGUI();
        gui.deserializeAccount();
        gui.displayGUI();
    }

    // all global components for JFrame
    JTextArea statusArea;
    JCheckBox isLockedCheckBox;
    JList depositAmount;
    JList withdrawAmount;
    JButton depositButton;
    JButton withdrawButton;
    JButton saveAccountButton;

    private void displayGUI() {
        JFrame frame = new JFrame("Virtual Bank v3.3");

        Integer[] intList = { 1, 2, 5, 10, 20, 50 };

        JPanel rightPanel = new JPanel();
        rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.Y_AXIS));
        rightPanel.setBackground(Color.GREEN);

        JPanel centerPanel = new JPanel();
        centerPanel.setBackground(Color.GREEN);
        centerPanel.setLayout(new GridBagLayout());

        frame.add(BorderLayout.CENTER, centerPanel);
        frame.add(BorderLayout.EAST, rightPanel);

        // add some JLabel's
        JLabel depositAmountLabel = new JLabel("Deposit Amount:");
        JLabel withdrawAmountLabel = new JLabel("Withdraw Amount:");
        JLabel isLockedLabel = new JLabel("Lock account(True/False)");

        // finish components(center panel)
        statusArea = new JTextArea(25, 25);
        statusArea.setEditable(false);
        statusArea.setText(account.status);

        centerPanel.add(statusArea);

        // add this to panel
        isLockedCheckBox = new JCheckBox();
        // add this to panel

        // scrollers and Jlists
        // ***********************************************************************
        depositAmount = new JList(intList);
        JScrollPane scroller1 = new JScrollPane(depositAmount);
        scroller1
                .setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        scroller1
                .setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        depositAmount.setVisibleRowCount(1);
        depositAmount.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        withdrawAmount = new JList(intList);
        JScrollPane scroller2 = new JScrollPane(depositAmount);
        scroller2
                .setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        scroller2
                .setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        depositAmount.setVisibleRowCount(1);
        depositAmount.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        // ***********************************************************************

        depositButton = new JButton("Deposit Amount.");
        withdrawButton = new JButton("Withdraw Amount");
        saveAccountButton = new JButton("Save your Account");

        rightPanel.add(depositAmount);
        rightPanel.add(depositButton);

        frame.setSize(425, 650);
        frame.setVisible(true);
    }

    private void serializeAccount() {
        try {
            ObjectOutputStream objectStream1 = new ObjectOutputStream(
                    new FileOutputStream("bankAccounts.txt"));
            objectStream1.writeObject(account);
            objectStream1.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

BankAccount类:

package GUIs;

import java.io.Serializable;

public class BankAccount implements Serializable {

    private static final long serialVersionUID = -5341449653011848470L;

    int balance = 0;
    int userWallet = 0;
    String owner = "Foo Bar";

    String status = "Account Owner: " + owner + "\nAccount balance: $"
            + balance + "\nOwner Wallet Balance: $" + userWallet;
    boolean isLocked = false;

    public int withdraw(int amount) {
        balance -= amount;
        userWallet += amount;
        return userWallet;
    }

    public int deposit(int amount) {
        balance += amount;
        userWallet -= amount;
        return balance;
    }

    public int depositCashIntoWallet(int amount) {
        userWallet += amount;
        return userWallet;
    }

}

这是堆栈跟踪:

Exception in thread "main" java.lang.NullPointerException
    at GUIs.BankGUI.displayGUI(BankGUI.java:85)
    at GUIs.BankGUI.main(BankGUI.java:49)

2 个答案:

答案 0 :(得分:6)

堆栈跟踪几乎可以准确地告诉您问题所在。你的BankGUI班的第85行有一个NullPointerException。如果我的IDE是正确的,那么第85行就是这一行

statusArea.setText(account.status);

这里只有2件事可以为空。 statusArea和帐户。由于您在使用之前初始化statusArea,因此必须为account

您需要在使用之前初始化帐户。

BankAccount account = new BankAccount();

我可以看到你尝试在try catch块中初始化account

try {
        ObjectInputStream objectStream2 = new ObjectInputStream(
                new FileInputStream("bankAccounts.txt"));
        account = (BankAccount) objectStream2.readObject();
        objectStream2.close();
} catch (Exception e) {
        e.printStackTrace();
}

如果抛出异常account未初始化。请确保在您使用null之前不会引发异常或确保检查account

答案 1 :(得分:2)

一种可能性是用于序列化BankAccountbankAccounts.txt的文件可能已损坏。这可能是由于类本身被修改而发生的。在这种情况下,您可以暂时替换

account = (BankAccount) objectStream2.readObject();

account = new BankAccount();
deserializeAccount中的

。这将允许应用程序加载而不抛出NPE

添加ActionListener以致电serializeAccount并重新保存该文件。现在可以恢复deserializeAccount方法,应用程序应该能够加载bankAccounts.txt