I have an ArrayList of objects (A class called OrderItem). OrderItem has a toString() method in it.
I also have a GUI class in which I have a JList. I want to list all the toString()’s for the elements of the arrayLists.
I know that for an arrayList of strings you can make them show in a JList by using:
ArrayList<String> myArrayList = new ArrayList<String>();
myArrayList.add("Value1");
myArrayList.add("Value2");
myJList = new JList(myArrayList.toArray());
But I want to list the toString() methods of an object arrayList, i.e. have something like:
ArrayList<OrderItem> myArrayList = new ArrayList<OrderItem>();
myJList = new JList(myArrayList.toString());
I realise that there is a possibility that JList doesn’t support such a feature or that there is some sort of logic problem with this. If that is so could you inform me as to why? Because surely an arrayList of strings should work in a similar way to an object arrayList’s toString(). I merely want to be pulling out a String value for the elements and using those values for my list.
I’ve searched the web for an answer and have not been able to find one that helps me, so I’ve come here to try to get this resolved.
Thanks a lot!
By default,
JListshows thetoStringvalue of the object. So there is no need to convert your objects to strings.You can override that behavior of
JListif needed by creating custom cell renderers. See How to Use Lists for more details.