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.pswp.cn/news/371664.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/371664.shtml
英文地址,請注明出處:http://en.pswp.cn/news/371664.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

【NIO】之IO和NIO的區別

在Java1.4之前的版本,Java對I/O的支持并不完善,開發人員在開發高性能I/O程序的時候,會面臨以下幾個問題: 1、沒有數據緩存區,I/O性能存在問題 2、沒有C/C通道的概念,輸入和輸出流是相互獨立的不能復用 3、同…

Mono環境下訪問SSL

由于MONO沒有CA證書,所以訪問SSL鏈接(HTTPS)就會出錯,這時候只要強制訪問就可以。 using System.Net.Security;using System.Security.Authentication;using System.Security.Cryptography.X509Certificates; private static bool…

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…

java線程實現排序_【多線程實現快速排序】

快速排序算法實現文件QuickSort.javapackage quick.sort;import java.util.concurrent.Callable;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;public class QuickSort implements Callable{private int[] array;private final in…

使用Gitolite搭建Gitserver

Gitolite是一款Perl語言開發的Git服務管理工具。通過公鑰對用戶進行認證。并可以通過配置文件對些操作進行基于分支和路徑的精細控制。Gitolite採用的是SSH協議而且使用SSH公鑰認證。因此不管是管理員還是普通用戶。都須要對SSH有所了解。Gitolite的官網是:https://…

java任務分支和合并_合并/分支戰略

我會給出與Adarsh Shah相同的建議,因為在大多數情況下,2個分支(MAIN,RELEASE)就足夠了,并且使用feature branches用于你不想立即提交到MAIN的東西,因為它需要一段時間才能完全準備好測試 . 通過RELEASE,我指…

Spring安全:防止暴力攻擊

Spring Security可以為您做很多事情。 帳戶被封鎖,密碼鹽。 但是蠻力阻斷劑呢? 那是你必須自己做的。 幸運的是,Spring是一個非常靈活的框架,因此對其進行配置并不是什么大問題。 讓我向您展示一些如何針對Grails應用程序執行…

NopCommerce計劃任務

NopCommerce計劃任務轉載于:https://www.cnblogs.com/chenjz/p/6293210.html

簡單談談js中的MVC

MVC是什么? MVC是一種架構模式,它將應用抽象為3個部分:模型(數據)、視圖、控制器(分發器)。 本文將用一個經典的例子todoList來展開(代碼在最后)。 一個事件發生的過程&a…

BTrace:Java開發人員工具箱中的隱藏寶石

這篇文章是關于BTrace的 ,我正在考慮將其作為Java開發人員的隱藏寶藏。 BTrace是用于Java平臺的安全,動態跟蹤工具。 BTrace可用于動態跟蹤正在運行的Java程序(類似于DTrace,適用于OpenSolaris應用程序和OS)。 不久&am…

python 圖片轉視頻ffmpeg_python圖片轉視頻(opencv),ffmpeg壓縮視頻

要注意:1. 圖片傳視頻要自己設置幀率和分辨率2.讀取圖片后分辨率要resize為和視頻分辨率一樣才可以3.寫完.avi視頻后視頻比較大,用ffmpeg將avi視頻壓縮為mp4import cv2from cv2 import VideoWriter, VideoWriter_fourcc, imread, resizeimport osfrom su…

門面模式

門面模式的定義 門面模式(Facade Pattern)也叫做外觀模式,是一種比較常用的封裝模式,其定義如 下: Provide a unified interface to a set of interfaces in a subsystem.Facade defines a higher-level interface tha…

Mysql數據庫申請

前段時間大部門下新成立了一個推廣百度OCR、文字識別、圖像識別等科技能力在金融領域應用的子部門。因為部門剛成立,基礎設施和人力都是欠缺的。當時分到我們部門的任務是抽調一個人做新部門主站前端開發工作。本來說的是只負責頁面的開發工作。當我參加過需求品審會…

Spring–添加SpringMVC –第2部分

在上一部分中,我們為經理和員工實現了控制器。 既然我們知道了解決方法,我們將做很少(但僅做很少)更復雜的事情–任務和時間表的控制器。 因此,讓我們從org.timesheet.web開始。 TaskController 。 首先創建一個類&…

php 正則分隔_探討PHP函數split()如何使用正則表達式切割字符串

對于初學者來說,掌握PHP中常用函數的用法,是其繼續學習的基礎。今天我們就為大家詳細介紹有關PHP函數split()的一些使用方法,希望大家能通過這篇文章介紹的內容增加自己的知識庫。說明array split ( string $pattern, string $string [, int …

通用的ProtostuffSerializer for Java

以前使用 protobuf或protostuff的時候覺得很麻煩,每個類都要單獨定制,于是封裝了一個類。 同事測試過,性能和壓縮率都很好,尤其是相比json的序列化。 需注意:只支持Pojo類(即需要有get/set方法)…

SAS筆記(6) PROC MEANS和PROC FREQ

PROC MEANS和PRC FREQ在做描述性分析的時候很常用,用法也比較簡單,不過這兩個過程步的某些選項容易忘記,本文就梳理一下。 在進入正文前,我們先創建所需的數據集TEST_SCORES: DATA TEST_SCORES; INPUT COUNTY : $9. SC…

休眠:保存vs持久并保存或更新

save和saveOrUpdate之間的區別是什么或save和persist之間的區別是任何Hibernate面試中常見的面試問題,就像Hibernate中get和load方法之間的區別一樣。 Hibernate Session類提供了幾種通過save , saveOrUpdate和persist等方法將對象保存到數據庫中的方法。…

php搜索數據庫設計,PHP數據庫搜索功能設計

其實搜索功能的設計很簡單,幾行代碼就可以完成。下面是form表單。從表單發出的數據名為search,然后發送到../admin/article_SearchResult.php這個文件處理。下面講下article_SearchResult.php這個文件如何實現搜索。$searchs $_POST[‘search‘];?>…