How can we clear all selections in Java Swing JList?

Java 8Object Oriented ProgrammingProgramming

To clear all selections, use the List clearSelection() method in Java −

JList list = new JList(sports);
list.clearSelection();

Above, the elements in Sports array is a String array −

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

The following is an example to clear all selection 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[]= { "Cricket","Football","Hockey","Rugby"};
      list = new JList(sports);
      list.clearSelection();
      panel.add(list);
      frame.add(panel);
      frame.setSize(550,300);
      frame.setVisible(true);
   }
}

Output

raja
Published on 08-May-2019 16:18:12
Advertisements