简体   繁体   中英

How to get selected item in JList into a string

I'm having trouble actually retrieving items that I have stored in a JList . I am using Eclipse, which urges me to parametrize the JList , which I did ( String ), and I need a way to retrieve the values and store them in a String variable.

Initialization:

JList<String> songlist;

songlist = new JList<String>(list); //list is a DefaultListModel

User fills up JList with songs...

Then I try to retrieve selected song to display information about it:

String value = songlist.getSelectedItem().toString();

...and I get the error:

The method getSelectedItem() is undefined for the type JList

Same happens when I try getSelectedValue() and getElementAt() (paired with getSelectedIndex() )

Use getSelectedIndex () instead of getSelectedItem ()

No such method exist in JList,for more detail refer http://docs.oracle.com/javase/7/docs/api/javax/swing/JList.html

If your selection mode is SINGLE, use

  • public E getSelectedValue() - Returns the value for the smallest selected cell index; the selected value when only a single item is selected in the list. When multiple items are selected, it is simply the value for the smallest selected index. Returns null if there is no selection.

This is a convenience method that simply returns the model value for getMinSelectionIndex .

If your selection mode is MULTIPLE, use

  • public List<E> getSelectedValuesList() - Returns a list of all the selected items, in increasing order based on their indices in the list.

See JList API

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM