JList ListSelectionListener example

I need to work on this JList ListSelectionListener example some more, but I thought I'd share it in its current state, in case it will help anyone get started.

If you haven't used it before, a ListSelectionListener is a Listener that you add to a JList so you can tell what item(s) in the JList the user has selected. In the example below, I have a reference to an object named menulist, and I'm adding a ListSelectionListener to that JList object so I can perform a different action depending on which item in the JList the user selects.

JList ListSelectionListener example

Here's my current JList ListSelectionListener example source code:

/**
 * Add a listener to the menulist so we can handle events where
 * the user clicks on our menu items.
 */
private void addListenerToMenuList()
{
  menuList.addListSelectionListener(new ListSelectionListener()
  {
    public void valueChanged(ListSelectionEvent e)
    {
      if (e.getValueIsAdjusting() == false)
      {
        switch(menuList.getSelectedIndex())
        {
          case 0:
            // the user selected the first item in the list; display the 'ping' panel
            displayPanel(pingPanel, pingPanel.getHostTextField());
            break;
          case 1:
            // the user selected the first item in the list; display the 'traceroute' panel
            displayPanel(traceroutePanel, traceroutePanel.getHostTextField());
            break;
          default:
            break;
        }
      }
      else
      {
        System.out.println("I think the value is adjusting");
      }
    }
  });
}

The way I'm handling the actual event where the user clicks on a JList item isn't the best; there are certainly better ways than saying "0 means 'ping', 1 means 'traceroute', etc.", but I just started writing this Swing app, and that's the way it looks today.

I'll update this article as this area of code gets better, but for the time being, if it helps anyone else see how to implement a ListSelectionListener on a JList, that's cool.

(If it helps to know it, this code is for a Java/Swing GUI app that will make life easier for people trying to debug networking problems, hence the references to a 'ping panel' and a 'traceroute panel'. In the current design, I'm using a JList as the main menu for this app.)