Java Null Pointer Exception on JLIST
OK so I'm trying to output the current string from an array that was put into a list... However when I click on the list I get a NullPointerException... :\
Help? :)
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) {
}
}
Thank you.
Change this line:
JList list = new JList(listModel);
into this line:
list = new JList(listModel);
You are creating a local variable list
in your constructor and thus hide the list
field of your class. So the field lisTry.list
stays null, hence the NullPointerException
.
精彩评论