Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get text element inside JList to a variable?

Tags:

java

swing

jlist

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!
}
like image 934
3D-kreativ Avatar asked Jan 18 '12 09:01

3D-kreativ


People also ask

How do I select multiple items in JList?

Multiple selection list enables the user to select many items from a JList. A SINGLE_INTERVAL_SELECTION list allows selection of a contiguous range of items in the list by clicking the first item, then holding the Shift key while clicking the last item to select in the range.

Is JList scrollable?

JList doesn't support scrolling directly. To create a scrolling list you make the JList the viewport view of a JScrollPane.


1 Answers

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

like image 191
Robin Avatar answered Oct 25 '22 15:10

Robin