I'm trying to get a Jlist to display a list of my own Client objects. My Client class DOES have a toString() method which works fine with System.out.print(), and I'm not sure where else my problem could lie.
Here is my code:
private void displayClients(){
List<Client> clients = new ArrayList<>(this.gym.getClients());
displayClientsList.setListData(clients);
displayClientsList.setSelectedIndex(0);
}
Here is the error message:
no suitable method found for setListData(List<Client>)
method JList.setListData(String[]) is not applicable
(argument mismatch; List<Client> cannot be converted to String[])
method JList.setListData(Vector<? extends String>) is not applicable
(argument mismatch; List<Client> cannot be converted to Vector<? extends String>)
Can anyone tell me how to fix this? Thanks :)
The API documents for this method says that it takes a Vector, or an array...
https://docs.oracle.com/javase/7/docs/api/javax/swing/JList.html#setListData(E[])
Try...
displayClientsList.setListData(clients.toArray(new Client[0]));
Or you might want to make a list of strings yourself and show those, for example...
List<String> displayList = clients.stream()
.map(c -> c.toString())
.collect(Collectors.toList());
displayClientsList.setListData(displayList.toArray(new String[0]));
A simple way to do this would be like this:
List<Client> clients = new ArrayList<>(this.gym.getClients());
String[] clientArray = new String[clients.size()];
displayClientsList.setListData(clients.toArray(clientArray));
Update: The JList
gets as a parameter a String
array, so you need to firstly convert your clients list to a String
array like this:
String[] clientAarray = clients.stream().map(c -> c.toString()).toArray(size -> new String[size]);
displayClientsList.setListData(clientArray);
Why don't you change displayClientsList
from a JList<String>
to a JList<Client>
and then do the following:
List<Client> clients = this.gym.getClients();
displayClientsList.setListData(clients.toArray(new Client[clients.size()]));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.