Why is this call to JList.clearSelection() giving me a null pointer exception?
this is the first time that I've posted but I tried to follow the guidelines and checked previous questions etc so any help on this would be much appreciated.
I have a JList called history which has a holds a list of strings representing simple mathematical equations (ie 2+2). I want to make it so that when you click on an item in the list it is then concatenated with another string in an input field, all of my methods work when I don't try to clear the selection (so that the same selection can be made multiple times) but when I try to use the clear selection method it throws a null pointer. here's the code where I'm calling it
import javax.swing.JList;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class HistoryListener implements ListSelectionListener {
JList history;
ListSelectionModel historySelection;
public HistoryListener(JList 开发者_运维百科history) {
this.history = history;
historySelection = history.getSelectionModel();
}
@Override
public void valueChanged(ListSelectionEvent select) {
if (select.getValueIsAdjusting()) {
NumListener.addHistory(history.getSelectedValue().toString());
}
if (history.isSelectionEmpty() == false) {
history.clearSelection();
}
}
}
if you need anymore info please let me know
cheers
if (select.getValueIsAdjusting()) {
As a guess, I think the above line of code should be if the value is NOT adjusting
Or if that doesn't work, then try wrapping the clearSelection() code in a SwingUtilities.invokeLater().
Actually the problem may be that when you clear the selection another valueChanged event is generated. This time the getSelectedValue will return a null value since nothing is selected. So you will probably need to add an if condition somewhere to handle this.
Otherwise a SSCCE is needed.
精彩评论