tags:

views:

42

answers:

1

OK so I'm trying to get the value of the selected of JList and I tried reading the API... I am using a DefaultListModule to store whats in my JList...

public DefaultListModel model = new DefaultListModel();

and a JList

public JList list;

and here is how I add:

model.addElement("Testing for this example");

and here is where I get NullPointerException:

Object dropped = model.getElementAt(list.getSelectedIndex());

and here is how I set-up my JLIST

    list = new JList(model);
    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    list.addMouseListener(this);
+3  A: 

If you get a NullPointerException either model or list is null. Since you postet the initialization of the model I'd guess that you didn't initialize the list itself.

public JList list = new JList(model);

Also make sure that getSelectedIndex doesn't return -1.

Raoul Duke
Whoops, I forgot to add that I already have that.
Dan
Oh, I know why! It's because I am removing it from the list THEN I get the name so I get NULL! :D
Dan
If you did that it's impossible that you get an NPE on this line: model.getElementAt(list.getSelectedIndex());. getElementAt only throws ArrayIndexOutOfBoundsException and getSelectedIndex never throws. Please post the stacktrace of the exception. Oh. Nevermind then.
Raoul Duke
So the problem was because you "removed it from the list". Where in the posted code do you display that line of code. There is no possible way we could have solved this problem based on the information provided in this question.
camickr