I have a swing GUI with a JList inside a JScrollPane and I've populated it with Strings. I want to get the selected String from the list but everytime it returns -1. I had also made selection listeners which didn't work. Looked up other ones from posts here but the listener is never fired no matter how much I click. Single selection mode is selected. Here's the button method. Value is null, index is -1.
loadSongBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int index=list.getSelectedIndex();
System.out.println("test "+list.getSelectedValue());
String name=(String)list.getModel().getElementAt(index); //works if i put a number
}
});
Here's the initialization:
private void initList(){
String[] songNames = extractSongs();
JList songsList=new JList(songNames); //tried to see if the problem is here
this.list=songsList;
}
private void createUIComponents() {
initList();
songListPane = new JScrollPane(list);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
}
Here's the SelectionListener just in case
list.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
JList<String> lst = (JList<String>) e.getSource();
String selection = lst.getSelectedValue();
System.out.println(selection);//doesnt go into the method at all in debug
}
}
});
Putting everything together it's working, so you probably messed up some variables (maybe you initialize a JList and register listeners there, then overvrite it in method initList()). Here a working example: