Java JList get selected value

Description

Java JList get selected value

import java.awt.Container;
import java.awt.FlowLayout;

import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class Main {
   public static void main(String args[]) throws Exception {
      JFrame f = new JFrame("java2s.com");
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      Container c = f.getContentPane();
      f.setSize(200, 80);/*from ww  w  . j  av a 2 s. co  m*/
      f.setLayout(new FlowLayout());
      String[] languages = { "Java", "C++", "C" };
      JList<String> list = new JList<>(languages);
      list.addListSelectionListener(new ListSelectionListener() {
         public void valueChanged(ListSelectionEvent e) {
            JList l = (JList) e.getSource();
            Object values[] = l.getSelectedValues();
            for (int i = 0; i < values.length; i++)
               System.out.println(values[i] + " ");
         }
      });
      c.add(new JScrollPane(list));
      f.pack();
      f.setVisible(true);
   }
}



PreviousNext

Related