How to set selection of items in JList?

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. We will see the methods which are used to change the set of selected items, when using these methods we select or deselect the items , List selection events are fired.

For selecting an item in the JList, JList provides a method setSelectionInterval which takes arguments to select specific item in a selection. If we want to select a single item in a JList then we both startSel and endSel will be same.

 
int startSel = 1;
int endSel = 1;
listToSet.setSelectionInterval(startSel, endSel);


If we want to select specific group of interval then we can specify endSel value greater than the startSle and less than the total number of elements in the JList.
 
startSel = 0;
endSel = 2;
listToSet.setSelectionInterval(startSel, endSel);

If we want to select first item then we can specify startSel and EndSel as 0.
 
startSel = 0;
endSel = 0;
listToSet.setSelectionInterval(startSel, endSel);


If we want to select all the elements in a JList then we can specify startSel and endSel as follows
 
startSel = 0;
endSel = listToSet.getModel().getSize()-1;
if (endSel >= 0) {
listToSet.setSelectionInterval(startSel, endSel);
}

For clearing all the selections in JList clearSelection method is provided
             
listToSet.clearSelection();


If we want to add another item or another selection interval then we can use the method addSelectionInterval . This method selects new items along with current selection.
             
startSel = 2;
endSel = 2;
listToSet.addSelectionInterval(startSel, endSel); // Add third item along with current selection.


When we want to remove any specific selection then we can use removeSelectionInterval method as follows :
 
startSel = 0;
endSel = 0;
listToSet.removeSelectionInterval(startSel, endSel);


These are the methods which we can use to set , add or remove the selection of a JList.
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