DefaultListModel修改jList视图 [英] DefaultListModel modify jList view
问题描述
如果我有以下情况
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屋!