Map集合可以保存键值映射关系,这非常适合本实例所需要的数据结构,所有省份信息可以保存为Map集合的键,而每个键可以保存对应的城市信息,本实例就是利用Map集合实现了省市级联选择框,当选择省份信息时,将改变城市下拉选择框对应的内容。
思路分析:
1. 创建全国(省,直辖市,自治区)映射集合,即LinkedHashMap对象,使用Map接口的put()方法向集合中添加指定的省与城市的映射关系,其中值为String型一维数组。
1 import java.util.LinkedHashMap; 2 import java.util.Map; 3 4 public class CityMap { 5 /** 6 * 全国(省,直辖市,自治区)映射集合 7 */ 8 public static Map<String,String[]> model=new LinkedHashMap<String, String[]>(); 9 static{ 10 model.put("北京", new String[]{"北京"}); 11 model.put("上海", new String[]{"上海"}); 12 model.put("天津", new String[]{"天津"}); 13 model.put("重庆", new String[]{"重庆"}); 14 model.put("黑龙江", new String[]{"哈尔滨","齐齐哈尔","牡丹江","大庆","伊春","双鸭山","鹤岗","鸡西","佳木斯","七台河","黑河","绥化","大兴安岭"}); 15 model.put("吉林", new String[]{"长春","延边","吉林","白山","白城","四平","松原","辽源","大安","通化"}); 16 model.put("辽宁", new String[]{"沈阳","大连","葫芦岛","旅顺","本溪","抚顺","铁岭","辽阳","营口","阜新","朝阳","锦州","丹东","鞍山"}); 17 model.put("内蒙古", new String[]{"呼和浩特","呼伦贝尔","锡林浩特","包头","赤峰","海拉尔","乌海","鄂尔多斯","通辽"}); 18 model.put("河北", new String[]{"石家庄","唐山","张家口","廊坊","邢台","邯郸","沧州","衡水","承德","保定","秦皇岛"}); 19 model.put("河南", new String[]{"郑州","开封","洛阳","平顶山","焦作","鹤壁","新乡","安阳","濮阳","许昌","漯河","三门峡","南阳","商丘","信阳","周口","驻马店"}); 20 model.put("山东", new String[]{"济南","青岛","淄博","威海","曲阜","临沂","烟台","枣庄","聊城","济宁","菏泽","泰安","日照","东营","德州","滨州","莱芜","潍坊"}); 21 model.put("山西", new String[]{"太原","阳泉","晋城","晋中","临汾","运城","长治","朔州","忻州","大同","吕梁"}); 22 model.put("江苏", new String[]{"南京","苏州","昆山","南通","太仓","吴县","徐州","宜兴","镇江","淮安","常熟","盐城","泰州","无锡","连云港","扬州","常州","宿迁"}); 23 model.put("安徽", new String[]{"合肥","巢湖","蚌埠","安庆","六安","滁州","马鞍山","阜阳","宣城","铜陵","淮北","芜湖","毫州","宿州","淮南","池州"}); 24 model.put("陕西", new String[]{"西安","韩城","安康","汉中","宝鸡","咸阳","榆林","渭南","商洛","铜川","延安"}); 25 model.put("宁夏", new String[]{"银川","固原","中卫","石嘴山","吴忠"}); 26 model.put("甘肃", new String[]{"兰州","白银","庆阳","酒泉","天水","武威","张掖","甘南","临夏","平凉","定西","金昌"}); 27 model.put("青海", new String[]{"西宁","海北","海西","黄南","果洛","玉树","海东","海南"}); 28 model.put("湖北", new String[]{"武汉","宜昌","黄冈","恩施","荆州","神农架","十堰","咸宁","襄樊","孝感","随州","黄石","荆门","鄂州"}); 29 model.put("湖南", new String[]{"长沙","邵阳","常德","郴州","吉首","株洲","娄底","湘潭","益阳","永州","岳阳","衡阳","怀化","韶山","张家界"}); 30 model.put("浙江", new String[]{"杭州","湖州","金华","宁波","丽水","绍兴","雁荡山","衢州","嘉兴","台州","舟山","温州"}); 31 model.put("江西", new String[]{"南昌","萍乡","九江","上饶","抚州","吉安","鹰潭","宜春","新余","景德镇","赣州"}); 32 model.put("福建", new String[]{"福州","厦门","龙岩","南平","宁德","莆田","泉州","三明","漳州"}); 33 model.put("贵州", new String[]{"贵阳","安顺","赤水","遵义","铜仁","六盘水","毕节","凯里","都匀"}); 34 model.put("四川", new String[]{"成都","泸州","内江","凉山","阿坝","巴中","广元","乐山","绵阳","德阳","攀枝花","雅安","宜宾","自贡","甘孜州","达州","资阳","广安","遂宁","眉山","南充"}); 35 model.put("广东", new String[]{"广州","深圳","潮州","韶关","湛江","惠州","清远","东莞","江门","茂名","肇庆","汕尾","河源","揭阳","梅州","中山","德庆","阳江","云浮","珠海","汕头","佛山"}); 36 model.put("广西", new String[]{"南宁","桂林","阳朔","柳州","梧州","玉林","桂平","贺州","钦州","贵港","防城港","百色","北海","河池","来宾","崇左"}); 37 model.put("云南", new String[]{"昆明","保山","楚雄","德宏","红河","临沧","怒江","曲靖","思茅","文山","玉溪","昭通","丽江","大理"}); 38 model.put("海南", new String[]{"海口","三亚","儋州","琼山","通什","文昌"}); 39 model.put("新疆", new String[]{"乌鲁木齐","阿勒泰","阿克苏","昌吉","哈密","和田","喀什","克拉玛依","石河子","塔城","库尔勒","吐鲁番","伊宁"}); 40 } 41 }
2. 定义获取省份的方法,创建一个Map集合,将上一步得到的映射集合赋值给它,使用Map集合的keySet()方法获取该集合中的所有键对象组成的Set集合,即为省分集合,创建一个Object型一维数组,使用Set接口的toArray()方法将Set集合转换为数组,返回此数组作为省份选择下拉列表的参数。
3. 使用JComboBox类的setModel()方法为省份下拉列表添加省份信息,参数即为上一步中的获取省份方法。
4. 定义根据省份获取市/县的方法,创建一个Map集合,将步骤1中得到的映射集合赋值给它,使用Map集合的get()方法获取指定键的值,即为市/县集合,创建一个String[]型一维数组,将市/县集合赋值给该数组。
5. 定义省份下拉列表的选项状态更改事件,在该事件中通过JComboBox类的getSelectedItem()方法获取选中的省份,默认为省份集合中的第一个值,然后使用JComboBox类的removeAllItems()方法清空市/县列表,根据选中的省份获取市/县数组,最后使用JComboBox的setModel()方法重新添加市/县列表的值。
1 import java.awt.Graphics; 2 import java.awt.Image; 3 4 import javax.swing.JPanel; 5 6 /** 7 * 带背景的面板组件 8 * 9 * @author ZhongWei Lee 10 */ 11 public class BackgroundPanel extends JPanel { 12 13 /** 14 * 15 */ 16 private static final long serialVersionUID = 7758689434195492602L; 17 /** 18 * 背景图片 19 */ 20 private Image image; 21 22 /** 23 * 构造方法 24 */ 25 public BackgroundPanel() { 26 super(); 27 setOpaque(false); 28 setLayout(null); 29 } 30 31 /** 32 * 设置图片的方法 33 */ 34 public void setImage(Image image) { 35 this.image = image; 36 } 37 38 @Override 39 protected void paintComponent(Graphics g) {// 重写绘制组件外观 40 if (image != null) { 41 int width = getWidth();// 获取组件大小 42 int height = getHeight(); 43 g.drawImage(image, 0, 0, width, height, this);// 绘制图片与组件大小相同 44 } 45 super.paintComponent(g);// 执行超类方法 46 } 47 }
1 import java.awt.Image; 2 import java.awt.Toolkit; 3 import java.io.BufferedInputStream; 4 import java.io.ByteArrayOutputStream; 5 import java.io.FileInputStream; 6 import java.io.IOException; 7 import java.io.InputStream; 8 import java.util.HashMap; 9 import java.util.Iterator; 10 import javax.swing.ImageIcon; 11 12 /** 13 * Utility class for managing resources such as colors, fonts, images, etc. 14 * 15 * This class may be freely distributed as part of any application or plugin. 16 * <p> 17 * Copyright (c) 2003 - 2004, Instantiations, Inc. <br>All Rights Reserved 18 * 19 * @author scheglov_ke 20 */ 21 public class SwingResourceManager { 22 23 /** 24 * Maps image names to images 25 */ 26 private static HashMap<String, Image> m_ClassImageMap = new HashMap<String, Image>(); 27 28 /** 29 * Returns an image encoded by the specified input stream 30 * @param is InputStream The input stream encoding the image data 31 * @return Image The image encoded by the specified input stream 32 */ 33 private static Image getImage(InputStream is) { 34 try { 35 ByteArrayOutputStream baos = new ByteArrayOutputStream(); 36 byte buf[] = new byte[1024 * 4]; 37 while (true) { 38 int n = is.read(buf); 39 if (n == -1) 40 break; 41 baos.write(buf, 0, n); 42 } 43 baos.close(); 44 return Toolkit.getDefaultToolkit().createImage(baos.toByteArray()); 45 } catch (Throwable e) { 46 return null; 47 } 48 } 49 50 /** 51 * Returns an image stored in the file at the specified path relative to the specified class 52 * @param clazz Class The class relative to which to find the image 53 * @param path String The path to the image file 54 * @return Image The image stored in the file at the specified path 55 */ 56 public static Image getImage(Class<?> clazz, String path) { 57 String key = clazz.getName() + '|' + path; 58 Image image = m_ClassImageMap.get(key); 59 if (image == null) { 60 if ((path.length() > 0) && (path.charAt(0) == '/')) { 61 String newPath = path.substring(1, path.length()); 62 image = getImage(new BufferedInputStream(clazz.getClassLoader().getResourceAsStream(newPath))); 63 } else { 64 image = getImage(clazz.getResourceAsStream(path)); 65 } 66 m_ClassImageMap.put(key, image); 67 } 68 return image; 69 } 70 71 /** 72 * Returns an image stored in the file at the specified path 73 * @param path String The path to the image file 74 * @return Image The image stored in the file at the specified path 75 */ 76 public static Image getImage(String path) { 77 return getImage("default", path); //$NON-NLS-1$ 78 } 79 80 /** 81 * Returns an image stored in the file at the specified path 82 * @param section String The storage section in the cache 83 * @param path String The path to the image file 84 * @return Image The image stored in the file at the specified path 85 */ 86 public static Image getImage(String section, String path) { 87 String key = section + '|' + SwingResourceManager.class.getName() + '|' + path; 88 Image image = m_ClassImageMap.get(key); 89 if (image == null) { 90 try { 91 FileInputStream fis = new FileInputStream(path); 92 image = getImage(fis); 93 m_ClassImageMap.put(key, image); 94 fis.close(); 95 } catch (IOException e) { 96 return null; 97 } 98 } 99 return image; 100 } 101 102 /** 103 * Clear cached images in specified section 104 * @param section the section do clear 105 */ 106 public static void clearImages(String section) { 107 for (Iterator<String> I = m_ClassImageMap.keySet().iterator(); I.hasNext();) { 108 String key = I.next(); 109 if (!key.startsWith(section + '|')) 110 continue; 111 Image image = m_ClassImageMap.get(key); 112 image.flush(); 113 I.remove(); 114 } 115 } 116 117 /** 118 * Returns an icon stored in the file at the specified path relative to the specified class 119 * @param clazz Class The class relative to which to find the icon 120 * @param path String The path to the icon file 121 * @return Icon The icon stored in the file at the specified path 122 */ 123 public static ImageIcon getIcon(Class<?> clazz, String path) { 124 return getIcon(getImage(clazz, path)); 125 } 126 127 /** 128 * Returns an icon stored in the file at the specified path 129 * @param path String The path to the icon file 130 * @return Icon The icon stored in the file at the specified path 131 */ 132 public static ImageIcon getIcon(String path) { 133 return getIcon("default", path); //$NON-NLS-1$ 134 } 135 136 /** 137 * Returns an icon stored in the file at the specified path 138 * @param section String The storage section in the cache 139 * @param path String The path to the icon file 140 * @return Icon The icon stored in the file at the specified path 141 */ 142 public static ImageIcon getIcon(String section, String path) { 143 return getIcon(getImage(section, path)); 144 } 145 146 /** 147 * Returns an icon based on the specified image 148 * @param image Image The original image 149 * @return Icon The icon based on the image 150 */ 151 public static ImageIcon getIcon(Image image) { 152 if (image == null) 153 return null; 154 return new ImageIcon(image); 155 } 156 }
1 import java.awt.EventQueue; 2 import java.awt.event.ItemEvent; 3 import java.awt.event.ItemListener; 4 import java.util.Map; 5 import java.util.Set; 6 7 import javax.swing.DefaultComboBoxModel; 8 import javax.swing.JButton; 9 import javax.swing.JComboBox; 10 import javax.swing.JFrame; 11 import javax.swing.JLabel; 12 import javax.swing.JPanel; 13 import javax.swing.JTextField; 14 import javax.swing.SwingConstants; 15 import javax.swing.UIManager; 16 import javax.swing.border.TitledBorder; 17 18 19 public class MainFrame extends JFrame { 20 21 /** 22 * 23 */ 24 private static final long serialVersionUID = -4595347311922711984L; 25 private JTextField textField_3; 26 private JTextField textField_1; 27 private JComboBox comboBox_1; 28 private JTextField textField; 29 private JComboBox cityComboBox; 30 private JComboBox comboBox; 31 32 /** 33 * Launch the application 34 * 35 * @param args 36 */ 37 public static void main(String args[]) { 38 EventQueue.invokeLater(new Runnable() { 39 public void run() { 40 try { 41 UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"); 42 MainFrame frame = new MainFrame(); 43 frame.setVisible(true); 44 } catch (Exception e) { 45 e.printStackTrace(); 46 } 47 } 48 }); 49 } 50 51 /** 52 * Create the frame 53 */ 54 public MainFrame() { 55 getContentPane().setLayout(null); 56 setBounds(100, 100, 518, 379); 57 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 58 //获取默认的市/县 59 String province=(String)getProvince()[0]; 60 setTitle("输入指定省/直辖市查询对应的市县"); 61 62 final BackgroundPanel backgroundPanel = new BackgroundPanel(); 63 backgroundPanel.setImage(SwingResourceManager.getImage(MainFrame.class, "/images/background.jpg")); 64 backgroundPanel.setBounds(0, 0, 510, 380); 65 getContentPane().add(backgroundPanel); 66 67 final JPanel panel = new JPanel(); 68 panel.setOpaque(false); 69 panel.setBounds(36, 126, 438, 70); 70 backgroundPanel.add(panel); 71 panel.setLayout(null); 72 panel.setBorder(new TitledBorder(null, "居住地", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null)); 73 cityComboBox = new JComboBox(); 74 cityComboBox.setBounds(245, 25, 124, 27); 75 panel.add(cityComboBox); 76 77 cityComboBox.setModel(new DefaultComboBoxModel(getCity(province))); 78 79 comboBox = new JComboBox(); 80 comboBox.setBounds(25, 25, 124, 27); 81 panel.add(comboBox); 82 comboBox.addItemListener(new ItemListener() { 83 public void itemStateChanged(final ItemEvent e) { // 选项状态更改事件 84 itemChange(); 85 } 86 }); 87 comboBox.setModel(new DefaultComboBoxModel(getProvince())); // 添加省份信息 88 89 final JLabel label = new JLabel(); 90 label.setText("省/直辖市"); 91 label.setBounds(155, 30, 66, 18); 92 panel.add(label); 93 94 final JLabel label_1 = new JLabel(); 95 label_1.setText("市/县"); 96 label_1.setBounds(375, 30, 37, 18); 97 panel.add(label_1); 98 99 final JLabel label_2 = new JLabel(); 100 label_2.setBounds(36, 43, 65, 18); 101 backgroundPanel.add(label_2); 102 label_2.setHorizontalAlignment(SwingConstants.RIGHT); 103 label_2.setHorizontalTextPosition(SwingConstants.LEADING); 104 label_2.setText("姓 名:"); 105 106 textField = new JTextField(); 107 textField.setBounds(113, 38, 154, 28); 108 backgroundPanel.add(textField); 109 110 final JLabel label_3 = new JLabel(); 111 label_3.setBounds(36, 84, 65, 18); 112 backgroundPanel.add(label_3); 113 label_3.setHorizontalAlignment(SwingConstants.RIGHT); 114 label_3.setHorizontalTextPosition(SwingConstants.LEADING); 115 label_3.setText("性 别:"); 116 117 comboBox_1 = new JComboBox(); 118 comboBox_1.setBounds(113, 81, 66, 25); 119 backgroundPanel.add(comboBox_1); 120 comboBox_1.setModel(new DefaultComboBoxModel(new String[] {"男", "女"})); 121 122 final JLabel label_4 = new JLabel(); 123 label_4.setBounds(36, 212, 65, 18); 124 backgroundPanel.add(label_4); 125 label_4.setHorizontalAlignment(SwingConstants.RIGHT); 126 label_4.setHorizontalTextPosition(SwingConstants.LEADING); 127 label_4.setText("详细地址:"); 128 129 textField_1 = new JTextField(); 130 textField_1.setBounds(113, 208, 367, 28); 131 backgroundPanel.add(textField_1); 132 133 final JLabel label_4_1 = new JLabel(); 134 label_4_1.setBounds(36, 252, 65, 18); 135 backgroundPanel.add(label_4_1); 136 label_4_1.setHorizontalTextPosition(SwingConstants.LEADING); 137 label_4_1.setHorizontalAlignment(SwingConstants.RIGHT); 138 label_4_1.setText("E-mail:"); 139 140 textField_3 = new JTextField(); 141 textField_3.setBounds(113, 248, 367, 27); 142 backgroundPanel.add(textField_3); 143 144 final JButton button = new JButton(); 145 button.setBounds(159, 289, 75, 28); 146 backgroundPanel.add(button); 147 button.setText("保存"); 148 149 final JButton button_1 = new JButton(); 150 button_1.setBounds(265, 289, 75, 28); 151 backgroundPanel.add(button_1); 152 button_1.setText("重置"); 153 // 154 } 155 156 /** 157 * 获取省、直辖市,自治区 158 * 159 * @return 160 */ 161 public Object[] getProvince() { 162 Map<String, String[]> map = CityMap.model;// 获取省份信息保存到Map中 163 Set<String> set = map.keySet(); // 获取Map集合中的键,并以Set集合返回 164 Object[] province = set.toArray(); // 转换为数组 165 return province; // 返回获取的省份信息 166 } 167 168 /** 169 * 获取指定省对应的市/县 170 * 171 * @param selectProvince 172 * @return 173 */ 174 public String[] getCity(String selectProvince) { 175 Map<String, String[]> map = CityMap.model; // 获取省份信息保存到Map中 176 String[] arrCity = map.get(selectProvince); // 获取指定键的值 177 return arrCity; // 返回获取的市/县 178 } 179 180 private void itemChange() { 181 String selectProvince = (String) comboBox.getSelectedItem(); 182 cityComboBox.removeAllItems(); // 清空市/县列表 183 String[] arrCity = getCity(selectProvince); // 获取市/县 184 cityComboBox.setModel(new DefaultComboBoxModel(arrCity)); // 重新添加市/县列表的值 185 } 186 187 }
效果如图: