Determine if the third item is selected in JList in Java
Description
The following code shows how to determine if the third item is selected in JList.
Example
// w w w .j av a 2 s . c o m
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
public class Main {
public Main() {
String languages[] = { "Java", "Perl", "java2s.com", "C++", "Basic", "C#" };
JList jlst = new JList(languages);
JFrame jfrm = new JFrame("Use JList");
jfrm.setLayout(new FlowLayout());
jfrm.setSize(200, 160);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jlst.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
boolean scrollIntoView = true;
jlst.setSelectedValue("Java", scrollIntoView);
int index = 2;
boolean isSel = jlst.isSelectedIndex(index);
jfrm.add(new JScrollPane(jlst));
jfrm.setSize(300, 300);
jfrm.setVisible(true);
}
public static void main(String args[]) {
new Main();
}
}
The code above generates the following result.
Home »
Java Tutorial »
Swing »
Java Tutorial »
Swing »