How to select an item from a JList without using a button?

advertisements

I've been making a program, and one part of it is the ability to choose an item from a JList and have it display a specific icon in a JLabel. I've made it work so that the user has to select the item from the list and then press a button to initiate the action.

I'm just wondering if there's any way to make it so the button isn't necessary? In other words, the user simply has to click the list item and it immediately initiates the action.


Here is my code:

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.FlowLayout;
import java.util.ArrayList;

import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class Example extends JFrame
{
  JList list = null;

  Example()
  {
    Container cp = getContentPane();

    cp.setLayout(new FlowLayout());
    ArrayList data = new ArrayList();

    data.add("Py");
    data.add("Piper");

    list = new JList(data.toArray());

    list.addListSelectionListener(new ListSelectionListener()
    {

      public void valueChanged(ListSelectionEvent evt)
      {
        // To avoid double value selected
        if (evt.getValueIsAdjusting())
                  return;
        System.out.println("Selected: " + list.getSelectedValue());
      }

    });

    cp.add(new JScrollPane(list), BorderLayout.CENTER);
  }

  public static void main(String[] s)
  {
    Example l = new Example();
    l.pack();
    l.setVisible(true);
  }
}

So right here:

list.addListSelectionListener(new ListSelectionListener()
{

    public void valueChanged(ListSelectionEvent evt)
    {
         // To avoid double value selected
         if (evt.getValueIsAdjusting())
            return;
         System.out.println("Selected: " + list.getSelectedValue());
    }

});

So what you are actually doing is to "plug" a ListSelectionListener to your JList so that can be notified for any events that occur to the JList. Within the valueChanged you add the code need to be executed when the user select something in the JList.