DefaultListModel modify jList view

大城市里の小女人 提交于 2019-12-13 04:29:12

问题


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


回答1:


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.

e.g.,

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);
   }
});


来源:https://stackoverflow.com/questions/22851358/defaultlistmodel-modify-jlist-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!