views:

26

answers:

1

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.

+4  A: 

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.

haffax
That returns the number in the array not name :\
Dan
Yes, because you call getSelectedIndex(), which returns the index. See Java API docs. When you want to see the list item text itself, call getSelectedValue() instead.
haffax