mjdcsy mjdcsy - 1 year ago 70
Java Question

getting values from JList without JButton

I want to get the value from my JList by using an ActionListener.
When user selects an index and the selected index updated, i want to get the updated value.

How can i do it without pressing a button? I want to add ActionListener to my JList.

Answer Source

How can i do it without pressing a button? I want to add ActionListener to my JList.

No, you really don't want to "add an ActionListener" to a JList since that is not allowed, since JList has no addActionListener(...) method, but you do need to add a listener, and which one is easily found by looking up the JList tutorial or the JList API. There you'll find your best option, a ListSelectionListener.

Useful resources:

For example:

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class ListListenerDemo extends JPanel {
    private static final String[] LIST_DATA = { "Sunday", "Monday", "Tuesday", "Wednesday",
            "Thursday", "Friday", "Saturday" };
    private JList<String> list = new JList<>(LIST_DATA);

    public ListListenerDemo() {

        // add the ListSelectionListener to our JList
        list.addListSelectionListener(new MyListListener()); 

        JScrollPane scrollPane = new JScrollPane(list);

    // here's our ListSelectionListener
    private class MyListListener implements ListSelectionListener {
        public void valueChanged(ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {
                JList<String> lst = (JList<String>) e.getSource();
                String selection = lst.getSelectedValue();
                if (selection != null) {
                    JOptionPane.showMessageDialog(list, selection, "Selected Item",

    private static void createAndShowGui() {
        ListListenerDemo mainPanel = new ListListenerDemo();

        JFrame frame = new JFrame("ListListenerDemo");

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());