JLIST上的Java空指针异常

时间:2010-07-16 18:47:03

标签: java applet nullpointerexception jlist

好的,所以我试图从放入列表的数组中输出当前字符串... 但是,当我点击列表时,我得到一个NullPointerException ...:\

帮助? :)

import java.applet.Applet;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;


public class lisTry extends JApplet implements MouseListener {

public static String newline;
public static JList list;

    public void init() {

            DefaultListModel listModel = new DefaultListModel();
            listModel.addElement("Debbie Scott");
            listModel.addElement("Scott Hommel");
            listModel.addElement("Alan Sommerer");

            JList list = new JList(listModel);


        this.getContentPane().add(list);

        list.addMouseListener(this);

        String newline = "\n";

        list.setVisible(true);

    }

    public void mousePressed(MouseEvent e) { }

    public void mouseReleased(MouseEvent e) {
       int index = list.getSelectedIndex();
       System.out.println("You clicked on: " + index);
    }

    public void mouseEntered(MouseEvent e) { }

    public void mouseExited(MouseEvent e) { }

    public void mouseClicked(MouseEvent e) { }

    public void paint(Graphics g) {

    } 
}

谢谢。

1 个答案:

答案 0 :(得分:5)

更改此行:

JList list = new JList(listModel);

进入这一行:

list = new JList(listModel);

您正在构造函数中创建局部变量list,从而隐藏类的list字段。因此,字段lisTry.list保持为空,因此NullPointerException