JList
In Swing, the basic list
class is called JList. It supports
the selection of one or more items from a list. Although the list often consists
of strings, it is possible to create a list of just about any object that can
be displayed. JList is so widely
used in Java that it is highly unlikely that you have not seen one before.
In the past, the items in a JList were represented as Object references. However, beginning
with JDK 7, JList was made generic
and is now declared like this:
class JList<E>
Here, E represents the type of the items in the list.
JList provides several constructors. The one used here is JList(E[ ] items)
This creates a JList that contains the items in the
array specified by items.
JList is based on two models. The first is ListModel. This interface defines how access to the list data is achieved. The second model is the ListSelectionModel interface, which
defines methods that determine what list item or items are selected.
Although a JList will work properly by itself,
most of the time you will wrap a JList
inside a JScrollPane. This way, long
lists will automatically be scrollable, which simplifies GUI design. It also makes
it easy to change the number of entries in a list without having to change the
size of the JList component.
A JList generates a ListSelectionEvent
when the user makes or changes a selection. This event is also generated when
the user deselects an item. It is handled by implementing ListSelectionListener. This listener specifies only one method,
called valueChanged( ), which is shown here:
void
valueChanged(ListSelectionEvent le)
Here, le is a reference to the event. Although ListSelectionEvent does provide some methods of its own, normally
you will interrogate the JList
object itself to determine what has occurred. Both ListSelectionEvent and ListSelectionListener
are packaged in javax.swing.event.
By default, a JList allows the user to select multiple
ranges of items within the list, but you can change this behavior by calling setSelectionMode( ), which is defined
by JList. It is shown here:
void setSelectionMode(int mode)
Here, mode specifies the selection mode. It must be one of these values
defined by
ListSelectionModel:
SINGLE_SELECTION
SINGLE_INTERVAL_SELECTION
MULTIPLE_INTERVAL_SELECTION
The default,
multiple-interval selection, lets the user select multiple ranges of items
within a list. With single-interval selection, the user can select one range of
items. With single selection, the user can select only a single item. Of
course, a single item can be selected in the other two modes, too. It’s just
that they also allow a range to be selected.
You can obtain the index of
the first item selected, which will also be the index of the only selected item
when using single-selection mode, by calling getSelectedIndex( ), shown here:
int getSelectedIndex( )
Indexing begins at zero. So,
if the first item is selected, this method will return 0. If no item is
selected, –1 is returned.
Instead of obtaining the
index of a selection, you can obtain the value associated with the selection by
calling getSelectedValue( ):
E getSelectedValue( )
It returns a reference to the
first selected value. If no value has been selected, it returns null. The following applet demonstrates
a simple JList, which holds a list
of cities. Each time
a city is selected in the
list, a ListSelectionEvent is generated,
which is handled by the valueChanged( ) method
defined by ListSelectionListener. It
responds by obtaining the index of
the selected item and displaying the name of the selected city in a label.
// Demonstrate JList.
import javax.swing.*; import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code="JListDemo" width=200
height=120> </applet>
*/
public class JListDemo extends JApplet {
JList<String> jlst;
JLabel jlab; JScrollPane jscrlp;
// Create an array of cities.
String Cities[] = { "New York",
"Chicago", "Houston", "Denver", "Los
Angeles", "Seattle", "London", "Paris",
"New Delhi", "Hong Kong", "Tokyo", "Sydney"
};
public void init() { try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() { makeGUI();
}
}
);
} catch (Exception exc) {
System.out.println("Can't create because
of " + exc);
}
}
private void makeGUI() {
///Change to flow layout.
setLayout(new FlowLayout());
//Create a JList.
jlst = new JList<String>(Cities);
//Set the list selection mode to single
selection.
jlst.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
//Add the list to a scroll pane.
jscrlp = new JScrollPane(jlst);
//Set the preferred size of the scroll pane.
jscrlp.setPreferredSize(new Dimension(120,
90));
//Make a label that displays the selection.
jlab =
new JLabel("Choose a City");
//Add selection listener for the list.
jlst.addListSelectionListener(new
ListSelectionListener() {
public void valueChanged(ListSelectionEvent le)
{
//Get the index of the changed item.
int idx = jlst.getSelectedIndex();
// Display selection, if item was selected.
if(idx != -1)
jlab.setText("Current selection: " +
Cities[idx]); else
// Otherwise, reprompt.
jlab.setText("Choose a City");
}
});
// Add the list and label to the content pane.
add(jscrlp);
add(jlab);
}
}
Output from the list example
is shown here:
Related Topics
Privacy Policy, Terms and Conditions, DMCA Policy and Compliant
Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.