Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

JList: How to programmatically select multiple items?

405 views
Skip to first unread message

Keng Ng

unread,
Sep 24, 1999, 3:00:00 AM9/24/99
to
Hi all,

Given a collection of objects which is a subset of the objects in a JList,
how do I *programmatically* select them in the list?

Calling setSelectedValue multiple times results in only the last item
being selected (even though the JList allows multiple interval selection),
while setSelectedIndices requires knowing the indices of the objects but
there doesn't seem to be a method in the API for getting those indices!?!

Short of going through every item in the list and checking if it is in the
collection, is there an easier way of doing it?


Thanks in advance,
Keng

Biju Thomas

unread,
Sep 24, 1999, 3:00:00 AM9/24/99
to
Keng Ng wrote:
>
>
> Given a collection of objects which is a subset of the objects in a JList,
> how do I *programmatically* select them in the list?
>
> Calling setSelectedValue multiple times results in only the last item
> being selected (even though the JList allows multiple interval selection),
> while setSelectedIndices requires knowing the indices of the objects but
> there doesn't seem to be a method in the API for getting those indices!?!
>

JList.getSelectedIndices() return the current set of selected indices.
Alternatively, you can use the method JList.getSelectedValues() which
will return the objects selected.

> Short of going through every item in the list and checking if it is in the
> collection, is there an easier way of doing it?
>

Clear the current selection with the method JList.clearSelection().
Then, you can use the methods JList.addSelectionInterval(int beginIndex,
int endIndex) to select the required items.

To find the index of an object, use DefaultListModel.indexOf( Object
element ) method. (The model is DefaultListModel by default. So, you can
type-cast the model of JList to DefaultListModel.)

--
Biju Thomas

0 new messages