[英]How to get JList to display ArrayList?
I'm trying to get a Jlist to display a list of my own Client objects. 我试图获取一个Jlist来显示我自己的Client对象的列表。 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.
我的Client类确实有一个toString()方法,该方法可以与System.out.print()一起正常工作,而且我不确定我的问题还可能在哪里。
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... 此方法的API文档说它需要一个Vector或一个数组...
https://docs.oracle.com/javase/7/docs/api/javax/swing/JList.html#setListData(E[]) 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: 更新:
JList
将String
数组作为参数,因此您首先需要将客户列表转换为String
数组,如下所示:
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: 为什么不将
displayClientsList
从JList<String>
更改为JList<Client>
,然后执行以下操作:
List<Client> clients = this.gym.getClients();
displayClientsList.setListData(clients.toArray(new Client[clients.size()]));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.