Skip to main content

Java List

Java List

The object of JList class represents a list of text items. The list of text items can be set up so that the user can choose either one item or multiple items. It inherits JComponent class. Lists can have many items, so they are often put in scrolls panes.



Jlist is always associate with INDEXing . the first item you add will have index 0, second item having index 1, third item will having index 2 and so on.

How to Create List
 Just Drag and Drop jlist from palette.

How to add item in List
Use model property from property window , as I already mentioned in combo box section.
Another way  to add tem in List is by using Default model. hear I am going to show you an 

example for this;
import javax.swing.DefaultListModel;
import javax.swing.JList;
public class Main {
  public static void main(String[] argv) throws Exception {
    DefaultListModel model = new DefaultListModel();
    JList list = new JList(model);
    // Initialize the list with items
    String[] items = { "A", "B", "C", "D" };
    for (int i = 0; i < items.length; i++) {
      model.add(i, items[i]);
    }
  }
}

Selectng Items in List
In three way you can select items :
1.      SINGLE_SELECTION:
Only one item can be selected at a time. When the user selects an item, any previously selected item is deselected first.

2.      SINGLE_INTERVAL_SELECTION:
Multiple, contiguous items can be selected. When the user begins a new selection range, any previously selected items are deselected first.


Multiple, contiguous items can be selected. When the user begins a new selection range, any previously selected items are deselected first.
3.    MULTIPLE_INTERVAL_SELECTION
The default. Any combination of items can be selected. The user must explicitly deselect items.



Now let discus few important Methods of jlist:



Methods
Description

getSelectedIndex()

Returns the smallest selected cell index; the selection when only a single item is selected in the list. When multiple items are selected, it is simply the smallest selected index. Returns -1 if there is no selection.

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.
getSelectedIndices()

Returns an array of all of the selected indices, in increasing order.
getSelectedValues()

Returns an array of all the selected values, in increasing order based on their indices in the list.


Comments