Get selected value from JList in Java

Description

The following code shows how to get selected value from JList.

Example


//from   w ww .  j  a v a2s.  c o  m
  
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;

public class Main {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Modifying Model");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // Fill model
    String labels[] = { "A", "java2s.com", "C", "D", "E", "F", "G" };
    final DefaultListModel<String> model = new DefaultListModel<String>();
    for (int i = 0, n = labels.length; i < n; i++) {
      model.addElement(labels[i]);
    }
    final JList<String> jlist = new JList<String>(model);
    JScrollPane scrollPane1 = new JScrollPane(jlist);
    frame.add(scrollPane1, BorderLayout.CENTER);

    JButton jb = new JButton("Add");

    jb.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent actionEvent) {
        System.out.println(jlist.getSelectedValue());
      }
    });

    frame.add(jb, BorderLayout.SOUTH);

    frame.setSize(640, 300);
    frame.setVisible(true);
  }
}

The code above generates the following result.

Get selected value from JList 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