2

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.

1
  • 2
    Just a note: > is used for marking up blockquotes; to mark up code you indent your snippets by 4 spaces. (I've made this change for you.) Commented Jul 16, 2010 at 18:49

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

That returns the number in the array not name :\
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.