【问题标题】:how to put an arraylist into a combobox in java?java - 如何将arraylist放入java中的组合框?
【发布时间】:2015-04-27 16:35:54
【问题描述】:
我的代码
for (Customer cusList1 : cusList) {
int numAcc = cusList1.getAccNo();
for (int c = 0; c<cusList.size(); c++) {
String arr [] = new String [numAcc];
arr[c] = cusList1.getName();
DefaultComboBoxModel RefCMB1 = new DefaultComboBoxModel(arr); //Assign Model data to ComboBoxes from Array
newNameCombo.setModel(RefCMB1);
}
}
我在数组列表中有客户详细信息,我想将名称放到组合框中。
cusList 是 ArrayList 的名称。 newNameCombo 是组合框的名称。
【问题讨论】:
标签:
java
arrays
oop
arraylist
combobox
【解决方案1】:
为方便起见,您可以使用 Vector 代替,尽管它被认为有点过时。
顺便说一句,您是否将名称存储在
ArrayList<String>
或一个
ArrayList<Customer>
?对于前者,您可以尝试:
ArrayList<String> list = ...
JComboBox<String> comboBox = new JComboBox<>(new Vector<>(list));
,如果你不介意的话,或者从一开始就使用 Vector。
我更喜欢泛型。确实,使用数组构建JComboBox也是有效的。
对于后一种,您可能希望使用 DefaultListCellRenderer。见this。覆盖 getListCellRendererComponent() 以将 Customer 添加到您的 JComboBox 并自己呈现。 (这是更理想的方式,因为您可以直接设置和检索 Customer。)
编辑:根据您的代码,我建议这样做:
JComboBox<Customer> comboBox = new JComboBox<>(new Vector<>(cusList));
comboBox.setRenderer(new DefaultListCellRenderer() {
@Override
public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
JLabel label = (JLabel)super.getListCellRendererComponent(list,value,index,isSelected,cellHasFocus);
label.setText(((Customer)value).getName());
return label;
}
});
【解决方案2】:
您可以使用 java.util.Vector 代替 ArrayList。 Vector一般是一个同步的(线程安全的)ArrayList,它也实现了List接口。此外,对 Vector 所做的更改将在 JComboBox 中可见。
Vector<String> data = new Vector<>();
data.add("a");
data.add("b");
JComboBox<String> jComboBox = new JComboBox<>(data);
data.add("c");
【解决方案3】:
您不能用 ArrayList 填充 DefaultComboBoxModel。
您需要将列表转换为数组或向量并传递给构造函数。
JComboBox cmb_box = new JComboBox(cusList.toArray());