Java Program to select the first item in JList

Java 8Object Oriented ProgrammingProgramming

To select the first item in JList, use setSelectionInterval() method:

String values[]= { "One","Two","Three","Four","Five","Six"};
JList list = new JList(values);
int begn = 0;
int end = 0;
list.setSelectionInterval(begn, end);

The following is an example to select the first item 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 values[]= { "One","Two","Three","Four","Five","Six"};
      list = new JList(values);
      int begn = 0;
      int 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 12:39:11
Advertisements