java citymap_Java实现Map集合二级联动

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

思路分析:

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

import Java.util.LinkedHashMap;

import java.util.Map;

public class CityMap {

/**

* 全国(省,直辖市,自治区)映射集合

*/

public static Map model=new LinkedHashMap();

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

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);// 执行超类方法

}

}

--------------------------------------------------------------------------------------

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.

*

* Copyright (c) 2003 - 2004, Instantiations, Inc.
All Rights Reserved

*

* @author scheglov_ke

*/

public class SwingResourceManager {

/**

* Maps image names to images

*/

private static HashMap m_ClassImageMap = new HashMap();

/**

* 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 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);

}

}

--------------------------------------------------------------------------------------------

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 map = CityMap.model;// 获取省份信息保存到Map中

Set set = map.keySet(); // 获取Map集合中的键,并以Set集合返回

Object[] province = set.toArray(); // 转换为数组

return province; // 返回获取的省份信息

}

/**

* 获取指定省对应的市/县

*

* @param selectProvince

* @return

*/

public String[] getCity(String selectProvince) {

Map 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)); // 重新添加市/县列表的值

}

}

效果如图:

d8b362a2dcd618530cdbbdaca7e7f34d.png

0b1331709591d260c1c78e86d0c51c18.png

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/371664.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

JavaOne 2012:使用HTML5和Java构建移动应用程序

我返回了Parc 55 (任务会议室),观看Max Katz的( Exadel开发人员关系)“用HTML5和Java构建移动应用程序” Bird-of-Feather(BoF)演示。 具体来说,Katz在Tiggzi (基于云的应…

HDU 2602.Bone Collector-动态规划0-1背包

Bone Collector Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 85530 Accepted Submission(s): 35381 Problem DescriptionMany years ago , in Teddy’s hometown there was a man who was called “Bone Col…

简单谈谈js中的MVC

MVC是什么? MVC是一种架构模式,它将应用抽象为3个部分:模型(数据)、视图、控制器(分发器)。 本文将用一个经典的例子todoList来展开(代码在最后)。 一个事件发生的过程&a…

BTrace:Java开发人员工具箱中的隐藏宝石

这篇文章是关于BTrace的 ,我正在考虑将其作为Java开发人员的隐藏宝藏。 BTrace是用于Java平台的安全,动态跟踪工具。 BTrace可用于动态跟踪正在运行的Java程序(类似于DTrace,适用于OpenSolaris应用程序和OS)。 不久&am…

Spring–添加SpringMVC –第2部分

在上一部分中,我们为经理和员工实现了控制器。 既然我们知道了解决方法,我们将做很少(但仅做很少)更复杂的事情–任务和时间表的控制器。 因此,让我们从org.timesheet.web开始。 TaskController 。 首先创建一个类&…

2016 Android Top 10 Library

过去的 2016 年,开源社区异常活跃,很多个人与公司争相开源自己的项目,让人眼花缭乱,然而有些项目只是昙花一现,有些项目却持久创造价值,为开发者提供了极大的便利,这些终究由时间来判断。今天&a…

您在eXo平台上的第一个Juzu Portlet

菊珠是佛教的佛珠。 一句话,我相信您已经学到了什么,印象深刻吗? 好的,我在这里不谈论佛教。 Juzu还是一个用于快速开发Portlet(以及即将推出的独立应用程序)的新框架。 您可以在Juzu网站上找到所需的所有…

Spring注入方式及注解配置

一:基于xml的DI(Dependency Injection) 注入类型: 定义学生Student实体类和小汽车Car实体类:进行封装和生成ToString(),并自定义属性Car Student 123456789101112131415161718192021222324252627282930313233343536373…

修改readonly属性的值

一般情况下,readonly属性的值是无法修改的,但可以通过特殊方式修改。定义一个student的类,其中name属性为readonly类型的变量 interface JFStudent : NSObjectproperty(nonatomic,copy,readonly) NSString *hisName;property(nonatomic,copy)…

ReactNative开发环境

此内容根据徐赢老师的文档整理后写处 原版地址:https://tuomaxu.gitbooks.io/reactnative/content/ ReactNative是跨平开发的解决方案,在开发平台的选择上,mac平台和win平台都可以。 所需要工具如下: 1,Nodejs环境 2&a…

MediaInfo源代码分析 1:整体结构

博客地址:http://blog.csdn.net/leixiaohua1020/article/details/12016231 MediaInfo源代码分析系列文章列表: MediaInfo源代码分析 1:整体结构MediaInfo源代码分析 2:API函数MediaInfo源代码分析 3:Open()函数MediaI…

射线碰撞检测

在我们的游戏开发过程中,有一个很重要的工作就是进行碰撞检测。例如在射击游戏中子弹是否击中敌人,在RPG游戏中是否捡到装备等等。在进行碰撞检测时,我们最常用的工具就是射线,Unity 3D的物理引擎也为我们提供了射线类以及相关的函…

php注册登录遍写入 遍验证,自动注册登录验证机制的php代码

在phpwind站点后台添加“广告管家”(CNZZ的一款广告投放的应用)的应用,整个“广告管家”通过iframe载入,载入的具体内容根据不同站点显示针对该站点的具体内容。出于意用性方面的考虑,需要以下二点:1、首次进入“广告管家”页面自…

Apache Wicket:记住我的功能

在Web应用程序中,具有“记住我”功能非常普遍,该功能使用户每次访问我们的网站时都能自动登录。 可以使用Spring Security来实现这种功能,但我认为将基于请求的身份验证框架与基于组件的Web框架结合使用并不是最好的主意。 这两个世界不能很好…

Ubuntu 安装中文

系统环境: 1. 官网 http://pinyin.sogou.com/linux/ 下载安装包。 2. 先运行 apt-get update 。 3. 再运行 apt-get -f install 。 4. 再运行 可能有的UBuntu系统自带了。 5. 如果下载的搜狐输入法安装包的格式为 .deb 的, 运行 : dpk…

JSF组件库–质量不只是零缺陷

自从我上次研究三个主要JSF组件库的质量以来,已经有一段时间了。 2009年12月,我开始比较RichFaces,Primefaces和ICEfaces的整体软件质量 。 从那时起,事情发生了变化,从现在开始,我想重新评估和更新它。 我…

字符串匹配(KMP 算法 含代码)

主要是针对字符串的匹配算法进行解说 有关字符串的基本知识传统的串匹配法模式匹配的一种改进算法KMP算法网上一比較易懂的解说小样例1计算next 2计算nextval代码有关字符串的基本知识 串(string或字符串)是由零个或多个字符组成的有限序列,一…

serialVersionUID的作用以及如何用idea自动生成实体类的serialVersionUID

转载:http://blog.csdn.net/liuzongl2012/article/details/45168585 serialVersionUID的作用: 通过判断实体类的serialVersionUID来验证版本一致性的。在进行反序列化时,JVM会把传来的字节流中的serialVersionUID与本地相应实体类的serialVer…

JBoss BRMS最佳实践– BPM流程初始化层的提示

我过去发布过一些有关迁移策略的文章,仔细研究了流程层,并提供了一些有关jBPM的最佳实践 ,它们都涉及到BPM策略的非常具体的部分。 我想重新讨论最佳实践的主题,然后在智能集成企业级别上,我们讨论使用JBoss BRMS对您的…

跨站点脚本(XSS)和预防

如OWASP网站(https://www.owasp.org/index.php/Cross-site_Scripting_(XSS))所述,跨站点脚本(XSS)攻击的变种几乎是无限的。 在这里,我建议使用基于Servlet筛选器的解决方案来清理HTTP请求。 攻…