Java Program to select all the items in a JList

Java 8Object Oriented ProgrammingProgramming

To select all the items in a JList, use setSelectionInterval() and set a range:

JList list = new JList(sports);
int begn = 0;
int end = list.getModel().getSize() - 1;
if (end >= 0) {
   list.setSelectionInterval(begn, end);
}

The following is an example to select all the items in a 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[]= {"Football","Fencing","Cricket","Squash","Hockey","Rugby"};
      list = new JList(sports);
      int begn = 0;
      int end = list.getModel().getSize() - 1;
      if (end >= 0) {
         list.setSelectionInterval(begn, end);
      }
      panel.add(list);
      frame.add(panel);
      frame.setSize(550,300);
      frame.setVisible(true);
   }
}

Output

raja
Published on 02-May-2019 09:06:14
Advertisements