Swing JList

In this tutorial you will learn about the Swing JList and its application with practical example.

Swing JList

It is a component which displays list of item and allows users to select one or more items. It is easy to display an array or Vector objects , using the JList constructor that automatically build a read-only instance for you. Let’s simply understand it by below simple code. In below code explained that how can we create jList and can add array and vector data in JList.

JList Class Declaration

JList Constructor

Let’s get more understand about JComboBox, Some of important constructor are listed below.

Recommended:-  Swing JTextField

JList () : This constructor construct a new JList with an empty, read-only model.

JList (ListModel<E> dataModel): This constructor is used to construct a JList that displays the elements from the specified, not-null , model.

JList (E[] listData): This constructor is used to construct a JList in which displays the elements in the specified array.

JComboBox(Vector<? eExtends w> listData): This constructor is used to construct a JList that displays elements in the specified vector.

 

JList Methos

Some of commonly used methods are listed below. It will help to know more about JList.

void addListSelectionListener(ListSelectionListener listener): This method is used to add a listener to the list, which notified each time a change to the selection occurs.

void clearSelection(): This method is used to clear the selection.

int getFirstVisibleIndex(): It returns an integer value of smallest list index that is currently visible.

ListModel<E> getModel(): This method is used to returns the displayed items of JListComponent which holds by the data model.

int getSelectedIndex(): This method is used to get the smallest selected cell index, and when single item selected in the list.

E getSelectedValue(): This method returns the value of smallest selected cell index .

List<E> getSelectedValuesList(): This method is used to returns the list of selected items.

String getToolTipText(MouseEvent event): This method is used to returns tool tip text.

void setListData(Vector<? extends E> listData): This method is used to create a read-only ListModel from a Vector.

void setListData(E[] listData): This method is used to create a read-only ListModel from an array of items..

 

void setSelectedIndex(int index): This method used to selects the single cell.

Recommended:-  Swing JButton

void setSelectionBackground(Color selectionBackground): This method is used to sets the color used to draw the background of selected items.

Example :-

An simple example to get understand about JList. Hopefully this will work for you.

Output :-

Output of this code will look like below image. You just need to copy this code and paste it in you program.

image001

In this tutorial we have learn about the Swing JList and its application with practical example. I hope you will like this tutorial.