Reputation: 15
So I have a GUI class and a class which will hold everything else. I have an ArrayList in the other class and I would like to populate the content of a Jlist in the GUI to the arraylist
I have this so far:
filmList = new JList(films.toArray());
getContentPane().add(filmList);
filmList.setBounds(27, 21, 638, 165);
It doesn't like just films.toArray() because it's in another class. What am I missing?
This is my FilmSystem class at the moment.
import java.util.ArrayList;
public class FilmSystem {
public FilmSystem() {
ArrayList<String> films = new ArrayList<String>();
films.add("A");
Upvotes: 0
Views: 1569
Reputation: 823
From the question its not clear, but if "films" is name of ArrayList in different class then you need to create the object of that class and then call the getter on it to get films and then use toArray on it. Like below:
FilmSystem filmObj=new FilmSystem();
filmList = new JList(filmObj.getterMethod.toArray(new String[0]));
where getterMethod should be name of the getter method you defined in class. If you have not defined getter method then you can directly call Arraylist on object.
If getter is not defined, then use following :
FilmSystem filmObj=new FilmSystem();
filmList = new JList(filmObj.films.toArray(new String[0]));
Upvotes: 1
Reputation: 44338
An array has an explicit type, independent of its elements' types. When constructing a JList<String>
you must pass an array whose type is String[], not Object[]. The zero-argument toArray()
method always returns an array whose type is Object[], even though the array's elements might all be of a particular class such as String.
To obtain an array of a particular type, pass an array of the desired type to the toArray
method:
filmList = new JList<String>(films.toArray(new String[0]));
Upvotes: 1