How to get Selected Items in JList Component?

JList is a component which enable user to select or deselect one or more items in a list. Lets see how we can select or deselect the components using JList.

1. Getting selected items in JList :

JList provides methods for both getting selected item objects or selected indices.

For getting the selected item object we can use following :
 
Object selFromList = listSelTest.getSelectedValue();

getSelectedValue value returns the value for the smallest selected index. If multiple items are selected then it returns the value of minimal index. If there is no selection then it returns as null.
 
Object[] selFromList = listSelTest.getSelectedValues();

getSelectedValues returns the array of selected objects and ordering of these object is based on the increasing number of selected indices. If nothing is selected then it simply returns the empty array.

2. Getting selected indices from JList

JList provides getSelectedIndex and getSelectedIndices methods to get the selected index or indices from JList.
 
int selFromList = listSelTest.getSelectedIndex();

getSelectedIndex returns the index of an selected item in a JList. If multiple items are selected then it simply returns smallest selected index. If nothing is selected then it returns -1.
 
int[] selFromList = listSelTest.getSelectedIndices();

getSelectedIndices returns the array of selected indices in increasing order. If nothing is selected in JList it returns an empty array. To get the selected items we can iterate over the selected items and get the items as shown below :

 
for ( int i=0; i < selFromList.length ; i++ ) {
Object sel = listSelTest.getModel().getElementAt(selFromList[i]);
}

We can get the object by using getElementAt( index ) method.

Suppose if we want the last selection index i.e. last selected item in a JList then we can use the method getMaxSelectionIndex which returns the largest value of the selected index.

 
int selFromList = listSelTest.getMaxSelectionIndex();

Similarly it provides getMinSelectionIndex method which returns the smallest value of selected indices.

If we want to check the list is empty or not then we can use method isSelectionEmpty()

 
boolean isSelected = listSelTest.isSelectionEmpty();

If nothing is selected it returns as true otherwise false. Similarly if we want to determine any specific index is selected or not then we can use method as

 
boolean isSelected = listSelTest.isSelectedIndex( 7 );

Where 7 is the index value which we are checking.
Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment