Get text element inside JList to a variable?

3D-kreativ picture 3D-kreativ · Jan 18, 2012 · Viewed 18k times · Source

Despite a lot of research I can't find an answer or solve how to get the selected text element inside a JList to a variable. Therefore I would preciate some help. I have tried to select the index of the selected element and removed elements with this code and that works fine, but as I wrote I want the selected text to a variable after pressing a button. Thanks!

int index = list.getSelectedIndex();
model.removeElementAt(index);

Parts of my JList code:

model = new DefaultListModel();
list = new JList(model);
list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
JScrollPane listScroller = new JScrollPane(list);
listScroller.setPreferredSize(new Dimension(430, 60));

Parts of my actionlistener code:

// Select customer
if(event.getSource() == buttonSelectCustomer){
int index = list.getSelectedIndex(); // Just for test
model.removeElementAt(index); // Just for test
int number = model.getSize(); // Just for test
//String selectedText = list.getSelectedValue(); // Not working!
}

Answer

Robin picture Robin · Jan 18, 2012

Use the ListModel#getElementAt(int) method with the currently selected index. If you are certain your model only contains String instances, you can directly cast it to a String as well