我的代码
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 是组合框的名称。
最佳答案
为了方便起见,您可以使用 Vector,尽管它被认为有点过时了。 顺便说一句,你是否将名称存储在
ArrayList<String>
或者
ArrayList<Customer>
?对于前一种,您可以尝试:
ArrayList<String> list = ...
JComboBox<String> comboBox = new JComboBox<>(new Vector<>(list));
,或者如果您不介意的话,从一开始就使用 Vector。 我更喜欢泛型。确实,使用数组构建 JComboBox 也是有效的。
对于后一种情况,您可能需要使用 DefaultListCellRenderer。请参阅this 。重写 getListCellRendererComponent() 以将 Customer 添加到 JComboBox 中并自行渲染它。 (这是更理想的方式,因为您可以直接设置和检索客户。)
编辑:根据您的代码,我建议这样做:
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;
}
});
关于java - 如何将数组列表放入java中的组合框中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28723166/