简体   繁体   中英

DefaultListModel modify jList view

If I have the following scenario

DefaultListModel model = new DefaultListModel();
model.addElement(file1.getName);
model.addElement(file2.getName);
...

//Add to list
myJList.setModel(model);

Now the list would obviously display the file name which is what I want. However if I were to process the files I would then need the actual path. So how would I achieve this outcome where the JList displays only the name but at the same time the model has stored the full path ?

Alternately I could of done ...(file1.getAbsolutePath()) but then the jList would not display the right data

You should instead use a DefaultListModel<File> and then add Files to the model, not file-name Strings. You can alter what the display looks like by giving the JList a cell renderer that has it just show each File's name.

eg,

fileList.setCellRenderer(new DefaultListCellRenderer(){
   @Override
   public Component getListCellRendererComponent(JList<?> list,
         Object value, int index, boolean isSelected, boolean cellHasFocus) {
      if (value != null) {
         value = ((File)value).getName();
      }
      return super.getListCellRendererComponent(list, value, index, isSelected,
            cellHasFocus);
   }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM