使用 JList 和 ListModel
我定义了一个 DirectoryListModel
类,它从 Java Api 扩展了 AbstractListModel
类。
在内部,我有一个 File
对象列表。我已将 getElementAt(int index)
方法定义为:
@Override
public Object getElementAt(int index) {
return directoryElements.get(index)
}
问题是,当我尝试使用 DirectoryListModel
运行 JList 时,它将显示完整路径文件的数量而不仅仅是文件名。我可以将此代码更改为:
@Override
public Object getElementAt(int index) {
return directoryElements.get(index).getName();
}
它会产生奇迹,但问题是在 onclick 事件中我想要文件对象,这样我就可以对它们进行一些检查(检查它们是否是目录等) 。 如果我让 getElementAt() 返回一个字符串,我就会失去这种可能性,因此我想知道是否有一种方法可以在 JList 在窗口中显示文件对象之前格式化它们或者是否有任何简单和优雅的方法来做到这一点。
谢谢
I have defined a DirectoryListModel
class that extends the AbstractListModel
class from the Java Api.
Internally, I have a list of File
objects. I have defined the getElementAt(int index)
method as:
@Override
public Object getElementAt(int index) {
return directoryElements.get(index)
}
The problem is that when I try to run my JList with my DirectoryListModel
, it is going to show up the full paths of files instead of just the filenames. I could change this code to:
@Override
public Object getElementAt(int index) {
return directoryElements.get(index).getName();
}
and it'd work wonders, but the problem is that in the onclick event I'll want to have the File objects so I can do some checking with them (check if they're directories, etc).
If I make getElementAt()
return a String, I'm losing that possibility, thus I'd like to konw if there is a way I can format my File objects before the JList shows them in my window or if is there any simple and elegant way of doing this.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我会扩展 DefaultListCellRenderer 以添加自定义代码,原因有两个:
a) 您将获得默认渲染器的默认行为,例如边框、行选择突出显示...
b) 渲染器(与所有 Swing 渲染器一样)已针对更快的绘制进行了优化。
阅读 Swing 教程中关于如何使用列表 有关渲染器的更多信息。
I would extend the DefaultListCellRenderer to add your custom code for two reasons:
a) you will get the default behaviour of the default renderer, like Borders, row selection highlighting...
b) The renderer (like all Swing renderers) has been optimized for faster painting.
Read the section from the Swing tutorial on How to Use Lists for more information on renderers.
对你来说最好的办法就是使用渲染器。正如您从名称中可以了解到的那样,渲染器用于在
MVC
范例中将V
播放到支持数据的M
。在这种情况下,您的File
是支持数据,渲染器用于仅显示File
中您想要显示的部分。如果您要实现自定义单元格渲染器,扩展
JLabel
并实现ListCellRenderer
,您可以通过实现如下所示的一个接口方法来进行简单的尝试:看一下
ListCellRenderer
javadoc 以获得更多指导。The best thing for you to do is to use renderers. Renderers, as you can gather from the name, are used to play the
V
to the backing data'sM
in theMVC
paradigm. In this case, yourFile
is the backing data, and the renderer is used to display just the part of theFile
that you want displayed.Were you to implement a custom cell renderer, extending a
JLabel
and implementingListCellRenderer
, you could start with a simple attempt by implementing the one interface method like this:Take a look at the
ListCellRenderer
javadoc for some more guidance.