Method to get JList from its ListSelection template


Is there a method in Java to get the JList if we know the ListSelectionModel? The code below is from a my ListSelectionListener:

    ListSelectionModel lsm=(ListSelectionModel)event.getSource();

    JList jl=lsm.someMethodIdLiketoKnow();

The ListSelectionListener is added onto this ListSelectionModel:


The other question is why wouldn't I just add the listener onto the JList directly and forget about the ListSelectionModel altogether?

It can't be possible to obtain "the" JList from a given ListSelectionModel, because there may be multiple lists that have the same ListSelectionModel:

import java.awt.BorderLayout;
import java.awt.GridLayout;

import javax.swing.DefaultListModel;
import javax.swing.DefaultListSelectionModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;

public class SharedListSelectionModel
    public static void main(String[] args)
        SwingUtilities.invokeLater(new Runnable()
            public void run()

    private static void createAndShowGUI()
        JFrame f = new JFrame();
        f.getContentPane().setLayout(new BorderLayout());

        DefaultListModel modelA = new DefaultListModel();
        JList listA = new JList(modelA);
        DefaultListModel modelB = new DefaultListModel();
        JList listB = new JList(modelB);
        for (int i=0; i<10; i++)

        ListSelectionModel selectionModel = new DefaultListSelectionModel();

        JPanel p = new JPanel(new GridLayout(1,2));
        p.add(new JScrollPane(listA));
        p.add(new JScrollPane(listB));
        f.getContentPane().add(p, BorderLayout.CENTER);


The selection model is a model on its own (roughly, in the meaning of the MVC pattern). But as icza pointed out in his answer: You can also add the selection listener to the JList.

Another solution is that you manually associate the listener and the list. Often, this can be done rather locally, in an anonymous inner class:

// Declare list as "final" (or make it a field of the enclosing class)
final JList list = ...;
list.getSelectionModel().addListSelectionListener(new ListSelectionListener()
    public void valueChanged(ListSelectionEvent e)
        // Can access the list here:
        Object object = list.getSelectedValue();