当我使用model.addElement(file)
将文件对象添加到用于创建JList的DefaultListModel时,JList中显示的文本是文件的路径。但是我只希望显示文件名。但是,我无法做model.addElement(file.getName())
,因为稍后需要访问文件对象,而不仅仅是字符串。
如何在仅显示文件名的同时将文件对象添加到列表/模型?谢谢!
答案 0 :(得分:3)
您可以通过创建自定义渲染器来实现:
class FileRenderer extends DefaultListCellRenderer
{
public Component getListCellRendererComponent(
JList list, Object value, int index, boolean isSelected, boolean cellHasFocus)
{
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
File file = (File)value;
setText( file.getName() );
return this;
}
}
然后使用以下命令为JList设置渲染器:
list.setCellRenderer( new FileRenderer() );
有关更多信息和工作示例,请参见Swing教程中位于Writing a Custom Cell Renderer上的部分
答案 1 :(得分:0)
一种丑陋的方法是创建自己的文件类,编辑toString()
方法。看看我的代码段:
import java.io.File;
class OwnFile extends File {
public OwnFile(String s) {
super(s);
}
@Override
public String toString() {
String url = super.toString();
String [] array = url.split("/");
return array[array.length-1];
}
}
以下是使用OwnFile
创建自己的JList的示例。这对于我的情况来说效果很好,并且仅在JList中显示spotify.txt
而不是src/spotify.txt
import javax.swing.*;
import java.io.File;
public class Main {
public Main(){
JFrame frame = new JFrame();
JList list = new JList();
list.setModel(new ListModel());
frame.add(list);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
class ListModel extends DefaultListModel<File>{
ListModel() {
addElement(new OwnFile("src/spotify.txt"));
}
}
public static void main(String[] args) {
new Main();
}
}