Syntax error Java Program to set Selection Mode for JList only for single selection

Java Program to set Selection Mode for JList only for single selection



To set single selection for JList, use DefaultListSelectionModel and set it to SINGLE_SELECTION:

String values[]= { "One","Two","Three","Four","Five","Six"};

JList list = new JList(values);
list.setSelectionMode(DefaultListSelectionModel.SINGLE_SELECTION);

The following is an example to set the selection mode for JList only for single selection:

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);
      list.setSelectionMode(DefaultListSelectionModel.SINGLE_SELECTION);
      panel.add(list);
      frame.add(panel);
      frame.setSize(550,300);
      frame.setVisible(true);
   }
}

The output is as follows. Now, you can only select a single item

Output

Updated on: 2019-07-30T22:30:26+05:30

458 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements