欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java实现Map集合二级联动示例

程序员文章站 2024-02-25 21:48:51
map集合可以保存键值映射关系,这非常适合本实例所需要的数据结构,所有省份信息可以保存为map集合的键,而每个键可以保存对应的城市信息,本实例就是利用map集合实现了省市级...

map集合可以保存键值映射关系,这非常适合本实例所需要的数据结构,所有省份信息可以保存为map集合的键,而每个键可以保存对应的城市信息,本实例就是利用map集合实现了省市级联选择框,当选择省份信息时,将改变城市下拉选择框对应的内容。

思路分析:

1. 创建全国(省,直辖市,自治区)映射集合,即linkedhashmap对象,使用map接口的put()方法向集合中添加指定的省与城市的映射关系,其中值为string型一维数组。

代码如下:

citymap.java

复制代码 代码如下:

import java.util.linkedhashmap;
import java.util.map;

public class citymap {
    /**
     * 全国(省,直辖市,自治区)映射集合
     */
    public static map<string,string[]> model=new linkedhashmap<string, string[]>();
    static{
        model.put("北京", new string[]{"北京"});
        model.put("上海", new string[]{"上海"});
        model.put("天津", new string[]{"天津"});
        model.put("重庆", new string[]{"重庆"});
        model.put("黑龙江", new string[]{"哈尔滨","齐齐哈尔","牡丹江","大庆","伊春","双鸭山","鹤岗","鸡西","佳木斯","七台河","黑河","绥化","大兴安岭"});
        model.put("吉林", new string[]{"长春","延边","吉林","白山","白城","四平","*","辽源","大安","通化"});
        model.put("辽宁", new string[]{"沈阳","大连","葫芦岛","旅顺","本溪","抚顺","铁岭","辽阳","营口","阜新","朝阳","锦州","丹东","鞍山"});
        model.put("内蒙古", new string[]{"呼和浩特","呼伦贝尔","锡林浩特","包头","赤峰","海拉尔","乌海","鄂尔多斯","通辽"});
        model.put("河北", new string[]{"石家庄","唐山","张家口","廊坊","邢台","邯郸","沧州","衡水","承德","保定","秦皇岛"});
        model.put("河南", new string[]{"郑州","开封","洛阳","平顶山","焦作","鹤壁","新乡","安阳","濮阳","许昌","漯河","三门峡","南阳","商丘","信阳","周口","驻马店"});
        model.put("山东", new string[]{"济南","青岛","淄博","威海","曲阜","临沂","烟台","枣庄","聊城","济宁","菏泽","泰安","日照","东营","德州","滨州","莱芜","潍坊"});
        model.put("山西", new string[]{"太原","阳泉","晋城","晋中","临汾","运城","长治","朔州","忻州","大同","吕梁"});
        model.put("江苏", new string[]{"南京","苏州","昆山","南通","太仓","吴县","徐州","宜兴","镇江","淮安","常熟","盐城","泰州","无锡","连云港","扬州","常州","宿迁"});
        model.put("安徽", new string[]{"合肥","巢湖","蚌埠","安庆","六安","滁州","马鞍山","阜阳","宣城","铜陵","淮北","芜湖","毫州","宿州","淮南","池州"});
        model.put("陕西", new string[]{"西安","韩城","安康","汉中","宝鸡","咸阳","榆林","渭南","商洛","铜川","延安"});
        model.put("宁夏", new string[]{"银川","固原","中卫","石嘴山","吴忠"});
        model.put("甘肃", new string[]{"兰州","白银","庆阳","酒泉","天水","武威","张掖","甘南","临夏","平凉","定西","金昌"});
        model.put("青海", new string[]{"西宁","海北","海西","黄南","果洛","玉树","海东","海南"});
        model.put("湖北", new string[]{"武汉","宜昌","黄冈","恩施","荆州","神农架","十堰","咸宁","襄樊","孝感","随州","黄石","荆门","鄂州"});
        model.put("湖南", new string[]{"长沙","邵阳","常德","郴州","吉首","株洲","娄底","湘潭","益阳","永州","岳阳","衡阳","怀化","韶山","张家界"});
        model.put("浙江", new string[]{"杭州","湖州","金华","宁波","丽水","绍兴","雁荡山","衢州","嘉兴","台州","舟山","温州"});
        model.put("江西", new string[]{"南昌","萍乡","九江","上饶","抚州","吉安","鹰潭","宜春","新余","景德镇","赣州"});
        model.put("福建", new string[]{"福州","厦门","龙岩","南平","宁德","莆田","泉州","三明","漳州"});
        model.put("贵州", new string[]{"贵阳","安顺","赤水","遵义","铜仁","六盘水","毕节","凯里","都匀"});
        model.put("四川", new string[]{"成都","泸州","内江","凉山","阿坝","巴中","广元","乐山","绵阳","德阳","攀枝花","雅安","宜宾","自贡","甘孜州","达州","资阳","广安","遂宁","眉山","南充"});
        model.put("广东", new string[]{"广州","深圳","潮州","韶关","湛江","惠州","清远","东莞","江门","茂名","肇庆","汕尾","河源","揭阳","梅州","中山","德庆","阳江","云浮","珠海","汕头","佛山"});
        model.put("广西", new string[]{"南宁","桂林","阳朔","柳州","梧州","玉林","桂平","贺州","钦州","贵港","防城港","百色","北海","河池","来宾","崇左"});
        model.put("云南", new string[]{"昆明","保山","楚雄","德宏","红河","临沧","怒江","曲靖","思茅","文山","玉溪","昭通","丽江","大理"});
        model.put("海南", new string[]{"海口","三亚","儋州","琼山","通什","文昌"});
        model.put("*", new string[]{"乌鲁木齐","阿勒泰","阿克苏","昌吉","哈密","和田","喀什","克拉玛依","石河子","塔城","库尔勒","吐鲁番","伊宁"});
    }
}

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()方法重新添加市/县列表的值。

    代码如下:

backgroundpanel.java

复制代码 代码如下:

import java.awt.graphics;
import java.awt.image;

import javax.swing.jpanel;

/**
 * 带背景的面板组件
 *
 * @author zhongwei lee
 */
public class backgroundpanel extends jpanel {

    /**
     *
     */
    private static final long serialversionuid = 7758689434195492602l;
    /**
     * 背景图片
     */
    private image image;

    /**
     * 构造方法
     */
    public backgroundpanel() {
        super();
        setopaque(false);
        setlayout(null);
    }

    /**
     * 设置图片的方法
     */
    public void setimage(image image) {
        this.image = image;
    }

    @override
    protected void paintcomponent(graphics g) {// 重写绘制组件外观
        if (image != null) {
            int width = getwidth();// 获取组件大小
            int height = getheight();
            g.drawimage(image, 0, 0, width, height, this);// 绘制图片与组件大小相同
        }
        super.paintcomponent(g);// 执行超类方法
    }
}

swingresourcemanager.java

复制代码 代码如下:

import java.awt.image;
import java.awt.toolkit;
import java.io.bufferedinputstream;
import java.io.bytearrayoutputstream;
import java.io.fileinputstream;
import java.io.ioexception;
import java.io.inputstream;
import java.util.hashmap;
import java.util.iterator;
import javax.swing.imageicon;

/**
 * utility class for managing resources such as colors, fonts, images, etc.
 *
 * this class may be freely distributed as part of any application or plugin.
 * <p>
 * copyright (c) 2003 - 2004, instantiations, inc. <br>all rights reserved
 *
 * @author scheglov_ke
 */
public class swingresourcemanager {

    /**
     * maps image names to images
     */
    private static hashmap<string, image> m_classimagemap = new hashmap<string, image>();

    /**
     * returns an image encoded by the specified input stream
     * @param is inputstream the input stream encoding the image data
     * @return image the image encoded by the specified input stream
     */
    private static image getimage(inputstream is) {
        try {
            bytearrayoutputstream baos = new bytearrayoutputstream();
            byte buf[] = new byte[1024 * 4];
            while (true) {
                int n = is.read(buf);
                if (n == -1)
                    break;
                baos.write(buf, 0, n);
            }
            baos.close();
            return toolkit.getdefaulttoolkit().createimage(baos.tobytearray());
        } catch (throwable e) {
            return null;
        }
    }

    /**
     * returns an image stored in the file at the specified path relative to the specified class
     * @param clazz class the class relative to which to find the image
     * @param path string the path to the image file
     * @return image the image stored in the file at the specified path
     */
    public static image getimage(class<?> clazz, string path) {
        string key = clazz.getname() + '|' + path;
        image image = m_classimagemap.get(key);
        if (image == null) {
            if ((path.length() > 0) && (path.charat(0) == '/')) {
                string newpath = path.substring(1, path.length());
                image = getimage(new bufferedinputstream(clazz.getclassloader().getresourceasstream(newpath)));
            } else {
                image = getimage(clazz.getresourceasstream(path));
            }
            m_classimagemap.put(key, image);
        }
        return image;
    }

    /**
     * returns an image stored in the file at the specified path
     * @param path string the path to the image file
     * @return image the image stored in the file at the specified path
     */
    public static image getimage(string path) {
        return getimage("default", path); //$non-nls-1$
    }

    /**
     * returns an image stored in the file at the specified path
     * @param section string the storage section in the cache
     * @param path string the path to the image file
     * @return image the image stored in the file at the specified path
     */
    public static image getimage(string section, string path) {
        string key = section + '|' + swingresourcemanager.class.getname() + '|' + path;
        image image = m_classimagemap.get(key);
        if (image == null) {
            try {
                fileinputstream fis = new fileinputstream(path);
                image = getimage(fis);
                m_classimagemap.put(key, image);
                fis.close();
            } catch (ioexception e) {
                return null;
            }
        }
        return image;
    }

    /**
     * clear cached images in specified section
     * @param section the section do clear
     */
    public static void clearimages(string section) {
        for (iterator<string> i = m_classimagemap.keyset().iterator(); i.hasnext();) {
            string key = i.next();
            if (!key.startswith(section + '|'))
                continue;
            image image = m_classimagemap.get(key);
            image.flush();
            i.remove();
        }
    }

    /**
     * returns an icon stored in the file at the specified path relative to the specified class
     * @param clazz class the class relative to which to find the icon
     * @param path string the path to the icon file
     * @return icon the icon stored in the file at the specified path
     */
    public static imageicon geticon(class<?> clazz, string path) {
        return geticon(getimage(clazz, path));
    }

    /**
     * returns an icon stored in the file at the specified path
     * @param path string the path to the icon file
     * @return icon the icon stored in the file at the specified path
     */
    public static imageicon geticon(string path) {
        return geticon("default", path); //$non-nls-1$
    }

    /**
     * returns an icon stored in the file at the specified path
     * @param section string the storage section in the cache
     * @param path string the path to the icon file
     * @return icon the icon stored in the file at the specified path
     */
    public static imageicon geticon(string section, string path) {
        return geticon(getimage(section, path));
    }

    /**
     * returns an icon based on the specified image
     * @param image image the original image
     * @return icon the icon based on the image
     */
    public static imageicon geticon(image image) {
        if (image == null)
            return null;
        return new imageicon(image);
    }
}

mainframe.java

复制代码 代码如下:

import java.awt.eventqueue;
import java.awt.event.itemevent;
import java.awt.event.itemlistener;
import java.util.map;
import java.util.set;

import javax.swing.defaultcomboboxmodel;
import javax.swing.jbutton;
import javax.swing.jcombobox;
import javax.swing.jframe;
import javax.swing.jlabel;
import javax.swing.jpanel;
import javax.swing.jtextfield;
import javax.swing.swingconstants;
import javax.swing.uimanager;
import javax.swing.border.titledborder;

 
public class mainframe extends jframe {

    /**
     *
     */
    private static final long serialversionuid = -4595347311922711984l;
    private jtextfield textfield_3;
    private jtextfield textfield_1;
    private jcombobox combobox_1;
    private jtextfield textfield;
    private jcombobox citycombobox;
    private jcombobox combobox;

    /**
     * launch the application
     *
     * @param args
     */
    public static void main(string args[]) {
        eventqueue.invokelater(new runnable() {
            public void run() {
                try {
                    uimanager.setlookandfeel("com.sun.java.swing.plaf.nimbus.nimbuslookandfeel");
                    mainframe frame = new mainframe();
                    frame.setvisible(true);
                } catch (exception e) {
                    e.printstacktrace();
                }
            }
        });
    }

    /**
     * create the frame
     */
    public mainframe() {
        getcontentpane().setlayout(null);
        setbounds(100, 100, 518, 379);
        setdefaultcloseoperation(jframe.exit_on_close);
        //获取默认的市/县
        string province=(string)getprovince()[0];
        settitle("输入指定省/直辖市查询对应的市县");

        final backgroundpanel backgroundpanel = new backgroundpanel();
        backgroundpanel.setimage(swingresourcemanager.getimage(mainframe.class, "/images/background.jpg"));
        backgroundpanel.setbounds(0, 0, 510, 380);
        getcontentpane().add(backgroundpanel);

        final jpanel panel = new jpanel();
        panel.setopaque(false);
        panel.setbounds(36, 126, 438, 70);
        backgroundpanel.add(panel);
        panel.setlayout(null);
        panel.setborder(new titledborder(null, "居住地", titledborder.default_justification, titledborder.default_position, null, null));
        citycombobox = new jcombobox();
        citycombobox.setbounds(245, 25, 124, 27);
        panel.add(citycombobox);

        citycombobox.setmodel(new defaultcomboboxmodel(getcity(province)));

        combobox = new jcombobox();
        combobox.setbounds(25, 25, 124, 27);
        panel.add(combobox);
        combobox.additemlistener(new itemlistener() {
            public void itemstatechanged(final itemevent e) { // 选项状态更改事件
                itemchange();
            }
        });
        combobox.setmodel(new defaultcomboboxmodel(getprovince())); // 添加省份信息

        final jlabel label = new jlabel();
        label.settext("省/直辖市");
        label.setbounds(155, 30, 66, 18);
        panel.add(label);

        final jlabel label_1 = new jlabel();
        label_1.settext("市/县");
        label_1.setbounds(375, 30, 37, 18);
        panel.add(label_1);

        final jlabel label_2 = new jlabel();
        label_2.setbounds(36, 43, 65, 18);
        backgroundpanel.add(label_2);
        label_2.sethorizontalalignment(swingconstants.right);
        label_2.sethorizontaltextposition(swingconstants.leading);
        label_2.settext("姓    名:");

        textfield = new jtextfield();
        textfield.setbounds(113, 38, 154, 28);
        backgroundpanel.add(textfield);

        final jlabel label_3 = new jlabel();
        label_3.setbounds(36, 84, 65, 18);
        backgroundpanel.add(label_3);
        label_3.sethorizontalalignment(swingconstants.right);
        label_3.sethorizontaltextposition(swingconstants.leading);
        label_3.settext("性    别:");

        combobox_1 = new jcombobox();
        combobox_1.setbounds(113, 81, 66, 25);
        backgroundpanel.add(combobox_1);
        combobox_1.setmodel(new defaultcomboboxmodel(new string[] {"男", "女"}));

        final jlabel label_4 = new jlabel();
        label_4.setbounds(36, 212, 65, 18);
        backgroundpanel.add(label_4);
        label_4.sethorizontalalignment(swingconstants.right);
        label_4.sethorizontaltextposition(swingconstants.leading);
        label_4.settext("详细地址:");

        textfield_1 = new jtextfield();
        textfield_1.setbounds(113, 208, 367, 28);
        backgroundpanel.add(textfield_1);

        final jlabel label_4_1 = new jlabel();
        label_4_1.setbounds(36, 252, 65, 18);
        backgroundpanel.add(label_4_1);
        label_4_1.sethorizontaltextposition(swingconstants.leading);
        label_4_1.sethorizontalalignment(swingconstants.right);
        label_4_1.settext("e-mail:");

        textfield_3 = new jtextfield();
        textfield_3.setbounds(113, 248, 367, 27);
        backgroundpanel.add(textfield_3);

        final jbutton button = new jbutton();
        button.setbounds(159, 289, 75, 28);
        backgroundpanel.add(button);
        button.settext("保存");

        final jbutton button_1 = new jbutton();
        button_1.setbounds(265, 289, 75, 28);
        backgroundpanel.add(button_1);
        button_1.settext("重置");
        //
    }

    /**
     * 获取省、直辖市,自治区
     *
     * @return
     */
    public object[] getprovince() {
        map<string, string[]> map = citymap.model;// 获取省份信息保存到map中
        set<string> set = map.keyset(); // 获取map集合中的键,并以set集合返回
        object[] province = set.toarray(); // 转换为数组
        return province; // 返回获取的省份信息
    }

    /**
     * 获取指定省对应的市/县
     *
     * @param selectprovince
     * @return
     */
    public string[] getcity(string selectprovince) {
        map<string, string[]> map = citymap.model; // 获取省份信息保存到map中
        string[] arrcity = map.get(selectprovince); // 获取指定键的值
        return arrcity; // 返回获取的市/县
    }

    private void itemchange() {
        string selectprovince = (string) combobox.getselecteditem();
        citycombobox.removeallitems(); // 清空市/县列表
        string[] arrcity = getcity(selectprovince); // 获取市/县
        citycombobox.setmodel(new defaultcomboboxmodel(arrcity)); // 重新添加市/县列表的值
    }

}

效果如图:

Java实现Map集合二级联动示例