1.重写的MyComboBox package com.jkj.utils.view.combobox; import com.jkj.utils.entity.CodeValue; import javax.swing.*; import java.util.List; public class MyComboBox extends JComboBox { public List<CodeValue> list; private String[] objArray; public MyComboBox(List<CodeValue> list) { this.list = list; objArray = new String[list.size()]; for (int i = 0; i < list.size(); i++) { objArray[i] = list.get(i).getValue(); } this.setModel(new javax.swing.DefaultComboBoxModel(objArray)); } public String getSelectedCode() { int index = getSelectedIndex(); return list.get(index).getCode(); } public String getSelectValue() { int index = getSelectedIndex(); return list.get(index).getValue(); } public void setSelectedByCode(String code) { int index = 0; for (int i = 0; i < list.size(); i++) { if (list.get(i).getCode().equals(code)) { index = i; break; } } this.setSelectedIndex(index); } public void setSelectedByValue(String value) { int index = 0; for (int i = 0; i < list.size(); i++) { if (list.get(i).getValue().equals(value)) { index = i; break; } } this.setSelectedIndex(index); } }
2.绑定Code和value
public class CodeValue { private String code; private String value; public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
3.用法
//获取所有的map值 java.util.List<Map<String, Object>> mapList = mapLogic.getMapList(); List<CodeValue> mapCodeList = new ArrayList<CodeValue>(); for (Map<String, Object> list : mapList) { CodeValue codeValue = new CodeValue(); codeValue.setCode((String) list.get("MapCode")); codeValue.setValue(codeValue.getCode()); mapCodeList.add(codeValue); } combMapCode = new MyComboBox(mapCodeList);