javaswingjlistdefaultlistmodel

Display Simple Name of File Object in JList


When I add a file object into a DefaultListModel, which is used to create a JList, with model.addElement(file), the displayed text in the JList is the path to the file. But I only want the file name to be displayed. I cannot do model.addElement(file.getName()), however, because I need access to the file object, not just a string, later on.

How can I add a file object to a list/model while displaying only the file name? Thank you!


Solution

  • You would do this by creating a custom renderer:

    class FileRenderer extends DefaultListCellRenderer
    {
        public Component getListCellRendererComponent(
            JList list, Object value, int index, boolean isSelected, boolean cellHasFocus)
        {
            super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
    
            File file = (File)value;
            setText( file.getName() );
    
            return this;
        }
    }
    

    Then you set the renderer for the JList using:

    list.setCellRenderer( new FileRenderer() );
    

    For more information and working examples see the section from the Swing tutorial on Writing a Custom Cell Renderer