我有一个ArrayList,它有很多对象。例如:
ArrayList<Supplier> a = new ArrayList<>();
正如您所看到的,这是一个来自类型Supplier
的ArrayList,它是一个具有4个属性(名称、公司、地址、电话号码)的类
public class Supplier {
public String name;
public String company;
public String address;
public String phone_no;
}
我想写JOptionPane.showInputDialog
语句,它在下拉列表中显示列表元素,以选择其中一个,在做出选择后,我想再次将该选择从同一类中划分为4个属性。
这是我的代码,但它不起作用:
String []choices = null;
for(int i = 0; i < a.size(); i++) {
choices[i] = a.get(i).toString();
}
JOptionPane.showInputDialog(null, "Choose supplier of the product !!", "Select Supplier", JOptionPane.QUESTION_MESSAGE,null, choices, "----");
尝试使用类似的东西:
ArrayList<Supplier> a = new ArrayList<>();
String[] choices = a.toArray();
String input = (String) JOptionPane.showInputDialog(null, "Choose now...",
"Choose supplier of the product !!", JOptionPane.QUESTION_MESSAGE, null,
choices, // Array of choices
choices[1]); // Initial choice
您使用的数组未初始化,导致NullPointerException
。
使用以下代码
String[] choices = a.toArray();
JOptionPane.showInputDialog(null, "Choose supplier of the product !!",
"Select Supplier", JOptionPane.QUESTION_MESSAGE, null, choices,
"----");
同时更新Supplier类中的toString()方法,如下所示:
@Override
public String toString() {
return "Supplier [name=" + name + ", company=" + company + ", address="
+ address + ", phone_no=" + phone_no + "]";
}
保留需要在下拉列表中显示的字段。
基于@Abdelhak的回答,我尝试了这个并为我工作:
首先假设数组列表已经有一些值,所以我们使用迭代器在数组列表中更快地循环,然后我使用迭代程序内部的循环来初始化字符串数组。
Iterator<Supplier> i = a.iterator();
String []choices = new String[a.size()];
while(i.hasNext())
{
for(int j = 0; j < a.size(); j++)
{
Supplier p = i.next();
choices[j] = p.getName() + " " + p.getCompany() + " " + p.getAddress() + " " + p.getPhone_no();
}
}
JOptionPane.showInputDialog(null, "Choose supplier of the product !!", "Select Supplier", JOptionPane.QUESTION_MESSAGE,null, choices, "----");