tags:

views:

50

answers:

2

I have defined a DirectoryListModel class that extends the AbstractListModel class from the Java Api.

Internally, I have a list of File objects. I have defined the getElementAt(int index) method as:

@Override
public Object getElementAt(int index) {
    return directoryElements.get(index)
}

The problem is that when I try to run my JList with my DirectoryListModel, it is going to show up the full paths of files instead of just the filenames. I could change this code to:

@Override
public Object getElementAt(int index) {
    return directoryElements.get(index).getName();

}

and it'd work wonders, but the problem is that in the onclick event I'll want to have the File objects so I can do some checking with them (check if they're directories, etc). If I make getElementAt() return a String, I'm losing that possibility, thus I'd like to konw if there is a way I can format my File objects before the JList shows them in my window or if is there any simple and elegant way of doing this.

Thanks

+2  A: 

The best thing for you to do is to use renderers. Renderers, as you can gather from the name, are used to play the V to the backing data's M in the MVC paradigm. In this case, your File is the backing data, and the renderer is used to display just the part of the File that you want displayed.

Were you to implement a custom cell renderer, extending a JLabel and implementing ListCellRenderer, you could start with a simple attempt by implementing the one interface method like this:

 public Component getListCellRendererComponent(JList list,
                                               Object value,
                                               int index,
                                               boolean isSelected,
                                               boolean cellHasFocus) {

     setText(((File)value).getName());
     return this;
 }

Take a look at the ListCellRenderer javadoc for some more guidance.

akf
+2  A: 

I would extend the DefaultListCellRenderer to add your custom code for two reasons:

a) you will get the default behaviour of the default renderer, like Borders, row selection highlighting...
b) The renderer (like all Swing renderers) has been optimized for faster painting.

class MyRenderer extends DefaultListCellRenderer
{
    public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus)
    {
        Component c = super.getListCellRendererComponent(list,value,index,false,false) ;
        JLabel label = (JLabel)c;

        label.setText(...);

        return c ;
    }
}

Read the section from the Swing tutorial on How to Use Lists for more information on renderers.

camickr