-5

我正在创建通讯簿,所有代码都已完成,但我不断收到错误消息!这是错误:

Exception in thread "main" java.lang.NullPointerException
at java.awt.Container.addImpl(Unknown Source)
at java.awt.Container.add(Unknown Source)
at javax.swing.JFrame.addImpl(Unknown Source)
at java.awt.Container.add(Unknown Source)
at MyAddressBook.<init>(MyAddressBook.java:40)
at MyAddressBook.main(MyAddressBook.java:31)

当我运行地址簿时,出现错误并且有一个空框架,框架没有读取内容,请运行代码,你会看到我在说什么。请建议我如何解决这个问题?

我的代码:

import javax.swing.*; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.event.ListSelectionEvent; import java.awt.event.*;  import java.awt.*; import java.io.*; public class AddressBook {

private JLabel lblFirstname,lblSurname, lblMiddlename,  lblPhone,
lblEmail,lblAddressOne, lblAddressTwo, lblCity, lblPostCode, lblPicture;
private JTextField txtFirstName, txtSurname, txtAddressOne, txtPhone,
txtMiddlename, txtAddressTwo, txtEmail, txtCity, txtPostCode;
private JButton btSave, btExit, btDelete;
private JList<String> list;
private DefaultListModel<String> listModel;
private JPanel panel;
PrintWriter out;

public static void main(String[] args) throws Exception{
    new AddressBook();
}

public AddressBook() throws Exception{
    JFrame frame = new JFrame("My Address Book");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(900,400);
    frame.setVisible(true);
    out = new PrintWriter (new BufferedWriter (new FileWriter("outfile.txt",true)));
    frame.add(panel); 
    frame.setVisible(true);
}
public void MyPanel() {
    panel = new JPanel();
    panel.setLayout(null);
    panel.setBackground(Color.cyan);

}
public void Fields () {
    lblFirstname = new JLabel("First name");
    lblFirstname.setBounds(135, 50, 150, 20);
    Font styleOne = new Font("Arial", Font.BOLD, 13);
    lblFirstname.setFont(styleOne);
    panel.add(lblFirstname);
    txtFirstName = new JTextField();
    txtFirstName.setBounds(210, 50, 150, 20);
    panel.add(txtFirstName);

    lblSurname = new JLabel ("Surname");
    lblSurname.setBounds(385,50,150,20);
    Font styleTwo = new Font ("Arial",Font.BOLD,13);
    lblSurname.setFont(styleTwo);
    panel.add(lblSurname);
    txtSurname = new JTextField();
    txtSurname.setBounds(450,50,150,20);
    panel.add(txtSurname);

    lblMiddlename = new JLabel ("Middle Name");
    lblMiddlename.setBounds(620,50,150,20);
    Font styleThree = new Font ("Arial", Font.BOLD,13);
    lblMiddlename.setFont(styleThree);
    panel.add(lblMiddlename);
    txtMiddlename = new JTextField();
    txtMiddlename.setBounds(710,50,150,20);
    panel.add(txtMiddlename);

    lblPhone = new JLabel("Phone");
    lblPhone.setBounds(160,100,100,20);
    Font styleFour = new Font ("Arial", Font.BOLD,13);
    lblPhone.setFont(styleFour);
    panel.add(lblPhone);
    txtPhone = new JTextField();
    txtPhone.setBounds(210,100,150,20);
    panel.add(txtPhone);

    lblEmail = new JLabel("Email");
    lblEmail.setBounds(410,100,100,20);
    Font styleFive = new Font ("Arial", Font.BOLD,13);
    lblEmail.setFont(styleFive);
    panel.add(lblEmail);
    txtEmail = new JTextField();
    txtEmail.setBounds(450,100,150,20);
    panel.add(txtEmail);

    lblAddressOne = new JLabel("Address 1");
    lblAddressOne.setBounds(145,150,100,20);
    Font styleSix = new Font ("Arial", Font.BOLD,13);
    lblAddressOne.setFont(styleSix);
    panel.add(lblAddressOne);
    txtAddressOne = new JTextField();
    txtAddressOne.setBounds(210,150,150,20);
    panel.add(txtAddressOne);

    lblAddressTwo = new JLabel("Address 2");
    lblAddressTwo.setBounds(145,200,100,20);
    Font styleSeven = new Font ("Arial", Font.BOLD,13);
    lblAddressTwo.setFont(styleSeven);
    panel.add(lblAddressTwo);
    txtAddressTwo = new JTextField();
    txtAddressTwo.setBounds(210,200,150,20);
    panel.add(txtAddressTwo);

    lblCity = new JLabel("City");
    lblCity.setBounds(180,250,100,20);
    Font styleEight = new Font ("Arial", Font.BOLD,13);
    lblCity.setFont(styleEight);
    panel.add(lblCity);
    txtCity = new JTextField();
    txtCity.setBounds(210,250,150,20);
    panel.add(txtCity);

    lblPostCode = new JLabel("Post Code");
    lblPostCode.setBounds(380,250,100,20);
    Font styleNine = new Font ("Arial", Font.BOLD,13);
    lblPostCode.setFont(styleNine);
    panel.add(lblPostCode);
    txtPostCode = new JTextField();
    txtPostCode.setBounds(450,250,150,20);
    panel.add(txtPostCode);
}
public void Image() {
    ImageIcon image = new ImageIcon("icon.png");
    lblPicture = new JLabel(image);
    lblPicture.setBounds(600,90, 330, 270);
    panel.add(lblPicture);
}
public void Buttons() {
    btSave = new JButton ("Save");
    btSave.setBounds(380,325,100,20);
    panel.add(btSave);
    btSave.addActionListener(new SaveListener(btDelete));

    btDelete = new JButton ("Delete");
    btDelete.setBounds(260,325,100,20);
    panel.add(btDelete);
    btDelete.addActionListener(new DeleteListener());

    btExit = new JButton ("Exit");
    btExit.setBounds(500,325,100,20);
    panel.add(btExit);
    btExit.addActionListener(new Action());
}
public void List() {
    listModel = new DefaultListModel<String>();
    listModel.addElement("Daniel Walker");
    listModel.addElement("John Smith");
    listModel.addElement("Bob Jones");

    //JList
    list = new JList<String>(listModel);
    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    list.setSelectedIndex(0);
    list.setVisibleRowCount(5);
    list.setBounds(0,10,125,350);
    panel.add(list);


}

static class Action implements ActionListener {
    public void actionPerformed(ActionEvent e) {
        JFrame option = new JFrame();
        int n = JOptionPane.showConfirmDialog(option, 
                "Are you sure you want to exit?", 
                "Exit?", 
                JOptionPane.YES_NO_OPTION);
        if(n == JOptionPane.YES_OPTION){
            System.exit(0);
        }
    }

}

class SaveListener implements ActionListener, DocumentListener {
    private boolean alreadyEnabled = false;
    private JButton button;

    public SaveListener(JButton button) {
        this.button = button;
    }

    //Required by ActionListener.
    public void actionPerformed(ActionEvent e) {

        String name = txtFirstName.getText();

        //User didn't type in a unique name...
        if (name.equals("") || alreadyInList(name)) {
            Toolkit.getDefaultToolkit().beep();
            txtFirstName.requestFocusInWindow();
            txtFirstName.selectAll();
            return;
        }

        int index = list.getSelectedIndex(); //get selected index
        if (index == -1) { //no selection, so insert at beginning
            index = 0;
        } else {           //add after the selected item
            index++;
        }

        listModel.insertElementAt(txtFirstName.getText() +" "+ txtSurname.getText(), index);
        //print to file
        out.println(txtFirstName.getText());
        out.println(txtSurname.getText());
        out.println(txtMiddlename.getText());
        out.println(txtPhone.getText());
        out.println(txtAddressOne.getText());
        out.println(txtAddressTwo.getText());
        out.println(txtEmail.getText());
        out.println(txtCity.getText());
        out.println(txtPostCode.getText());
        out.close();

        //Reset the text field.
        txtFirstName.requestFocusInWindow();
        txtSurname.requestFocusInWindow();
        txtMiddlename.requestFocusInWindow();
        txtPhone.requestFocusInWindow();
        txtAddressOne.requestFocusInWindow();
        txtAddressTwo.requestFocusInWindow();
        txtEmail.requestFocusInWindow();
        txtCity.requestFocusInWindow();
        txtPostCode.requestFocusInWindow();
        txtFirstName.setText("");
        txtSurname.setText("");
        txtMiddlename.setText("");
        txtPhone.setText("");
        txtAddressOne.setText("");
        txtAddressTwo.setText("");
        txtEmail.setText("");
        txtCity.setText("");
        txtPostCode.setText("");
        //Select the new item and make it visible.
        list.setSelectedIndex(index);
        list.ensureIndexIsVisible(index);
    }


    protected boolean alreadyInList(String name) {
        return listModel.contains(name);
    }

    //Required by DocumentListener.
    public void insertUpdate(DocumentEvent e) {
        enableButton();
    }

    //Required by DocumentListener.
    public void removeUpdate(DocumentEvent e) {
        handleEmptyTextField(e);
    }

    //Required by DocumentListener.
    public void changedUpdate(DocumentEvent e) {
        if (!handleEmptyTextField(e)) {
            enableButton();
        }
    }

    private void enableButton() {
        if (!alreadyEnabled) {
            button.setEnabled(true);
        }
    }

    private boolean handleEmptyTextField(DocumentEvent e) {
        if (e.getDocument().getLength() <= 0) {
            button.setEnabled(false);
            alreadyEnabled = false;
            return true;
        }
        return false;
    }
}

public void valueChanged(ListSelectionEvent e) {
    if (e.getValueIsAdjusting() == false) {
        if (list.getSelectedIndex() == -1) {
            btDelete.setEnabled(false);

        } else {
            btDelete.setEnabled(true);
        }
    }

}
class DeleteListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {

        int index = list.getSelectedIndex();
        listModel.remove(index);
        int size = listModel.getSize();
        if (size == 0) { 
            btDelete.setEnabled(false);
        } else { 
            if (index == listModel.getSize()) {
                index--;
            }
            list.setSelectedIndex(index);
            list.ensureIndexIsVisible(index);
        }

    }
}

}

4

1 回答 1

4

在这里,您将获得 NPE。您没有初始化面板。我想你忘了调用MyPanel方法。

frame.add(panel);     

解决这个NPE。

MyPanel();  //Call this method in constructor before this line.
frame.add(panel); 
于 2013-03-24T15:24:07.523 回答