Java Program to check if the second item is selected in Java JList


To check if the second item is selected i.e. index 1, use the method isSelectedIndex():

list.isSelectedIndex(1);

Above, we have set the list with string values:

String sports[]= { "Squash","Fencing","Cricket","Football","Hockey","Rugby"};

JList list = new JList(sports);

The following is an example to check if the second item is selected in JList:

Example

package my;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
class SwingDemo extends JFrame {
   static JFrame frame;
   static JList list;
   public static void main(String[] args) {
      frame = new JFrame("JList Demo");
      SwingDemo s = new SwingDemo();
      JPanel panel = new JPanel();
      String sports[]= {"Squash","Fencing","Cricket","Football","Hockey","Rugby"};
      list = new JList(sports);
      list.setSelectedIndex(1);
      boolean res = list.isSelectedIndex(1);
      System.out.println("Second item is selected? = "+res);
      panel.add(list);
      frame.add(panel);
      frame.setSize(550,300);
      frame.setVisible(true);
   }
}

Output

Updated on: 30-Jul-2019

73 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements