Java Swing JList
I'm trying to make a JList to display the contents of an array. 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 me开发者_StackOverflow社区thod)?
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
.
See: http://java.sun.com/docs/books/tutorial/uiswing/components/list.html
The JList is a MVC based control, like the rest of 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)).
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. It's bad practice. Easy enough to override DefaultListRenender to call Object.ToString() to be safe.
See here more JList info: http://java.sun.com/products/jfc/tsc/tech_topics/jlist_1/jlist.html
精彩评论