简体   繁体   English

Java Swing JList

[英]Java Swing JList

I'm trying to make a JList to display the contents of an array. 我试图使一个JList来显示数组的内容。 The array itself is not an array of strings, however, but an array of Objects. 数组本身不是字符串数组,而是对象数组。

Is it possible then, to use the same array of objects as the parameter to construct my JList (if the Objects are given a toString method)? 那么,是否有可能使用与参数相同的对象数组来构造我的JList(如果为对象提供了toString方法)?

Thanks. 谢谢。

Yes it is. 是的。

A list uses an object called a cell renderer to display each of its items. 列表使用称为单元格渲染器的对象来显示其每个项目。 The default cell renderer knows how to display strings and icons and it displays Objects by invoking toString . 默认的单元格渲染器知道如何显示字符串和图标,并通过调用toString显示对象。

See: http://java.sun.com/docs/books/tutorial/uiswing/components/list.html 请参阅: http : //java.sun.com/docs/books/tutorial/uiswing/components/list.html

The JList is a MVC based control, like the rest of Swing. JList是一个基于MVC的控件,与其他Swing一样。 You can pass the JList an object array, a string array, or a vector and then supply a ListCellRenderer to render it the objects that you passed in (by default the DefaultListRenderer is used (which is just a JLabel)). 您可以向JList传递对象数组,字符串数组或向量,然后提供ListCellRenderer来向其呈现您传入的对象(默认情况下,使用DefaultListRenderer (只是JLabel))。

I don't know what the default behavior if you don't set a ListRender to render the object if you don't pass in strings. 我不知道如果不设置StringRender而不设置ListRender来呈现对象,则默认行为是什么。 It's bad practice. 这是不好的做法。 Easy enough to override DefaultListRenender to call Object.ToString() to be safe. 很容易重写DefaultListRenender,以调用Object.ToString()是安全的。

See here more JList info: http://java.sun.com/products/jfc/tsc/tech_topics/jlist_1/jlist.html 在此处查看更多JList信息: http : //java.sun.com/products/jfc/tsc/tech_topics/jlist_1/jlist.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM