Working with Lists in Java

Working with Lists

The JLists class of JAVA is part of the Java Swing package. Lists are a way to represent several sets of data or information one after the other. Lists can be active as well as passive. Active lists will allow you to make selections (one or more) from the list. Buttons can be associated with the list to perform or trigger further events. JList is a component that inherits the JComponent class. To be able to use lists in your code, the following package needs to be imported:

import javax.swing.*;

JLists can be initialized with a set of constructors as mentioned below

  • JList(): This will create an empty list where you can add components.
  • JList(E[]I): All the elements of the array E will be added to the in the order followed by the index.
  • JList(ListModel d): Given the list model, a list will be initialized accordingly.
  • JList(Vector I): A list will be created with the elements of the vector I.

Some Common Methods Associated with Lists

  • getSelectedIndex(): Returns the index number of the selected item on the list.
  • getSelectedValue(): Returns the selected element on the list.
  • setSelectedIndex(int i): The selected index of the list will be set to i
  • setSelectionBackgroundColor(Color c): The list will be colored to the color ‘c’.

Example

Let us code a simple program that will show the various months of a year in a list format. To keep the code simple, we will not be adding an event to the list.

import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
class ListProg extends JFrame
{
static JFrame f;
static JList b;
public static void main (String args [])
{
f= new JFrame(“frame”);
ListProg lp = new ListProg();
JPanel p = new JPanel();
JLabel l = new JLabel (“Months of the Year”);
String months[] = {“January”, “February”, “March”, “April”, “May”, “June”, ”July”, “August”, “September”, “October”, “November”, “December”};
//Adding months to the list
b = new JList(months);
//To set a selected index
b.setSelectedIndex(2);
p.add(b);
f.add(p);
f.setSize(400,400);
f.show();
}
}

 

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.