问题
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