Listen to selection changed event for JList with ListSelectionListener in Java

Description

The following code shows how to listen to selection changed event for JList with ListSelectionListener.

Example


import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
//  ww w. j a va 2 s  .  c o m
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class Main extends JFrame implements ListSelectionListener {
  JLabel label = new JLabel("The fox jumps over the lazy dog.");

  public Main() {
    setTitle("ListTest: Press control to multi-select");
    setSize(400, 300);
    addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });

    String[] words = { "quick", "brown", "hungry", "wild", "silent", "huge" };

    JList wordList = new JList(words);
    JScrollPane scrollPane = new JScrollPane(wordList);

    JPanel p = new JPanel();
    p.add(scrollPane);
    wordList.addListSelectionListener(this);

    getContentPane().add(p, "South");
    getContentPane().add(label, "Center");
  }

  public void valueChanged(ListSelectionEvent evt) {
    JList source = (JList) evt.getSource();
    Object[] values = source.getSelectedValues();

    String text = "";
    for (int i = 0; i < values.length; i++) {
      String word = (String) values[i];
      text += word + " ";
    }
    label.setText("The " + text + "fox jumps over the lazy dog.");
  }

  public static void main(String[] args) {
    JFrame frame = new Main();
    frame.show();
  }
}

The code above generates the following result.

Listen to selection changed event for JList with  ListSelectionListener in Java




















Home »
  Java Tutorial »
    Swing »




Action
Border
Color Chooser
Drag and Drop
Event
Font Chooser
JButton
JCheckBox
JComboBox
JDialog
JEditorPane
JFileChooser
JFormattedText
JFrame
JLabel
JList
JOptionPane
JPasswordField
JProgressBar
JRadioButton
JScrollBar
JScrollPane
JSeparator
JSlider
JSpinner
JSplitPane
JTabbedPane
JTable
JTextArea
JTextField
JTextPane
JToggleButton
JToolTip
JTree
Layout
Menu
Timer