How to display a value when select a JList item in Java?


A JList is a subclass of JComponent class that allows the user to choose either a single or multiple selections of items. A JList can generate a ListSelectiionListener interface and it includes one abstract method valueChanged(). We can display a value when an item is selected from a JList by implementing MouseListener interface or extending MouseAdapter class and call the getClickCount() method with single-click event (getClickCount() == 1) of MouseEvent class.

Example

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class JListItemSeletionTest extends JFrame {
   private JList list;
   private JScrollPane jsp;
   private Vector data;
   public JListItemSeletionTest() {
      setTitle("JListItemSeletion Test");
      list = new JList();
      data = new Vector();
      data.addElement("India");
      data.addElement("Australia");
      data.addElement("England");
      data.addElement("England");
      data.addElement("New Zealand");
      data.addElement("South Africa");
      list.setListData(data);
      list.setSelectedIndex(0);
      list.addMouseListener(new MouseAdapter() {
         public void mouseClicked(MouseEvent me) {
            if (me.getClickCount() == 1) {
               JList target = (JList)me.getSource();
               int index = target.locationToIndex(me.getPoint());
               if (index >= 0) {
                  Object item = target.getModel().getElementAt(index);
                  JOptionPane.showMessageDialog(null, item.toString());
               }
            }
         }
      });
      jsp = new JScrollPane(list);
      add(jsp, BorderLayout.NORTH);
      setSize(400, 275);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   public static void main(String args[]) {
      new JListItemSeletionTest();
   }
}

Output

Updated on: 10-Feb-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements