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!
}
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.
JList doesn't support scrolling directly. To create a scrolling list you make the JList the viewport view of a JScrollPane.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With