Java JList set to single selection

Description

Java JList set to single selection

// Demonstrate JList. 
import java.awt.Dimension;
import java.awt.FlowLayout;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

class Demo extends JPanel {
   JList<String> jlst;
   JLabel jlab;/*from  ww  w  . j av a  2s  . c om*/
   JScrollPane jscrlp;

   public Demo() {

      // Create an array of cities.
      String Cities[] = { "New York", "Chicago", "Houston", "Denver", "Los Angeles", "Seattle", "London", "Paris",
            "New Delhi", "Hong Kong", "Tokyo", "Sydney" };
      setLayout(new FlowLayout());

      jlst = new JList<String>(Cities);

      // Set the list selection mode to single-selection.
      jlst.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

      // Add the list to a scroll pane.
      jscrlp = new JScrollPane(jlst);
      jscrlp.setPreferredSize(new Dimension(120, 90));

      jlab = new JLabel("Choose a City");
      jlst.addListSelectionListener(new ListSelectionListener() {
         public void valueChanged(ListSelectionEvent le) {
            int idx = jlst.getSelectedIndex();
            if (idx != -1)
               jlab.setText("Current selection: " + Cities[idx]);
            else // Othewise, reprompt.
               jlab.setText("Choose a City");

         }
      });
      add(jscrlp);
      add(jlab);
   }
}

public class Main {
   public static void main(String[] args) {
      Demo panel = new Demo();

      JFrame application = new JFrame();

      application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      application.add(panel);
      application.setSize(250, 250);
      application.setVisible(true);
   }
}



PreviousNext

Related