Monday, August 20, 2012

java swing : Getting the Selected Items in a JList Component

The following methods return the indices of the selected items:


// To create a list, see Creating a JList Component

// Get the index of all the selected items
int[] selectedIx = list.getSelectedIndices();

// Get all the selected items using the indices
for (int i=0; i<selectedIx.length; i++) {
    Object sel = list.getModel().getElementAt(selectedIx[i]);
}

// Get the index of the first selected item
int firstSelIx = list.getSelectedIndex();

// Get the index of the last selected item
int lastSelIx = list.getMaxSelectionIndex();

// Determine if the third item is selected
int index = 2;
boolean isSel = list.isSelectedIndex(index);

// Determine if there are any selected items
boolean anySelected = !list.isSelectionEmpty();

0 comments:

Post a Comment