How can I check if there are any selected items in Java JList

Java 8Object Oriented ProgrammingProgramming

To check if there are any selected items, use the following:

boolean res = !list.isSelectionEmpty();

The value of res would be TRUE IF we have a selected item in the JList.

The following is an example to check if there are any selected items 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(4);
      boolean res = !list.isSelectionEmpty();
      System.out.println(res);
      panel.add(list);
      frame.add(panel);
      frame.setSize(550,300);
      frame.setVisible(true);
   }
}

Output

The output in the console would be TRUE since we have found a selected item in the JList.

raja
Published on 02-May-2019 12:04:29
Advertisements