DefaultListModel修改jList视图 [英] DefaultListModel modify jList view

查看:263
本文介绍了DefaultListModel修改jList视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有以下情况

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

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

现在,列表显然将显示我想要的文件名.但是,如果要处理文件,则需要实际路径.那么在JList仅显示名称但模型同时存储完整路径的情况下,我将如何实现这一结果呢?

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 ?

或者我可以做...(file1.getAbsolutePath()),但是jList不会显示正确的数据

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

推荐答案

您应该改用DefaultListModel<File>,然后将文件添加到模型中,而不要添加文件名字符串.您可以通过为JList提供一个仅显示每个文件名称的单元格渲染器来更改显示的外观.

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.

例如

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

这篇关于DefaultListModel修改jList视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆