Java Tips Weblog

  • Blog Stats

    • 2,571,868 hits
  • Categories

  • Archives

List Action

Posted by Rob Camick on October 14, 2008

Many Swing components support the concept of invoking an Action when a certain event occurs. For example, clicking on a button will invoke its ActionListener, or using the Enter key on a text field will do the same. However, there is no standard support for invoking an Action on a JList. I find this surprising, as most applications I’ve worked with support invoking an Action when either the Enter key is pressed or when the mouse is double clicked.

Well, its not too difficult to add this support to a JList. The building blocks are all there. The Enter key can be supported by using Key Bindings and of course the double click can be handled by a MouseListener So all we need to do is put it all together, which is purpose of the ListAction class. All you need to worry about is creating an Action and this class will do the rest.

That’s all there is to say about this class, but I’ll leave you with a simple example:

Action displayAction = new AbstractAction()
{
public void actionPerformed(ActionEvent e)
{
JList list = (JList)e.getSource();
System.out.println(list.getSelectedValue());
}
};

String[] data = { “zero”, “one”, “two”, “three”, “four”, “five” };
JList list = new JList( data );
ListAction la = new ListAction(list, displayAction);

Of course you can use any KeyStroke (instead of the Enter key) to activate the Action. Before doing so you may want to check out my Key Bindings program to make sure you aren’t using a keyStroke that is already mapped to an Action.

Get The Code

ListAction.java

See Also

List Editor
Key Bindings

Related Reading

How to Use Actions
How to Use Key Bindings
How to Write a Mouse Listener

3 Responses to “List Action”

  1. Nick said

    A list is not a visual component, so I don’t understand the purpose of this. Do you have an example how this could be used ?

  2. Rob Camick said

    This class is designed to make it easier to add an Action to a JList. You write the Action. The class will manage the MouseListener and Key Bindings for you. Check out the List Editor Action. A link has been added to the “See Also” section.

  3. Nick said

    I misread your post. You’re talking about javax.swing.JList, not java.util.List. Sorry.

Leave a comment