Posted by Rob Camick on October 19, 2008
Wouldn’t it be nice to be able to edit the values in a JList? Well a list was designed to be display only so it would involve a major rewrite of the component to support this requirement. For this reason, the most common suggestion found in the forums is to create a single column JTable and use it as a list. This is a very powerfull solution as you inherit all the default rendering and editing capabilities of a table. But what if you just want simple editing of the values, is there another way?
I might just have a solution for you. It was inspired by a posting in the Java forums about making a table header editable. The solution uses a JPopupMenu with a JTextField for the editor. The popup is positioned over the row that was selected so it looks like you are editing the list in place. You change the value and then save it to the list using the Enter key. Or, you can cancel the editor at any time by using the Escape key like you can in any popup.
The default implementation has some restrictions to using it:
- you must use the DefaultListModel
- only String data will be saved back to the list
Still interested? The EditListAction class is easily added to the list as the default Action, by using it together with the ListAction class discussed in an earlier blog entry. The following code was used to create the editor pictured in the image:
Action edit = new EditListAction();
ListAction la = new ListAction(list, edit);
If you need to change the default implementation to support a different ListModel or data type then you need to extend EditListAction and make the following changes:
- specify the ListModel you need by using the setModelClass(…) method
- override the applyValueToModel(…) method to match your requirements