Java Implementation Map set two-level linkage example _java

Source: Internet
Author: User
Tags set set

The map collection can hold key-value mapping relationships, this is very suitable for this example of the data structure required, all the province information can be saved as a key to the map collection, and each key can save the corresponding city information, this example is the use of map collection to achieve the provincial and municipal cascade selection box, when the province information selection, Will change the contents of the City Drop-down selection box.

Thinking Analysis:

1. Create a national (provincial, municipal, autonomous) mapping collection, the Linkedhashmap object, that uses the put () method of the map interface to add the specified province-city mapping relationship to the collection, where the value is a string one-dimensional array.

The code is as follows:

Citymap.java

Copy Code code as follows:



Import Java.util.LinkedHashMap;


Import Java.util.Map;





public class Citymap {


/**


* Map Collection of national (province, municipality, Autonomous Region)


*/


public static map<string,string[]> model=new linkedhashmap<string, string[]> ();


static{


Model.put ("Beijing", New string[]{"Beijing"});


Model.put ("Shanghai", New string[]{"Shanghai"});


Model.put ("Tianjin", new string[]{"Tianjin"});


Model.put ("Chongqing", New string[]{"Chongqing"});


Model.put ("Heilongjiang"), New string[]{"Harbin", "Qiqihar", "Mudanjiang", "Daqing", "Yichun", "Shuangyashan", "Hegang", "Jixi", "Jiamusi", "Qitaihe", "Heihe", "Suihua", "daxinganling"});


Model.put ("Jilin", New string[]{"Changchun", "Yanbian", "Jilin", "Bss", "Baicheng", "Siping", "Songyuan", "Liaoyuan", "Da-an", "Tonghua"});


Model.put ("Liaoning", New string[]{"Shenyang", "Dalian", "Huludao", "Lushun", "Benxi", "Fushun", "Tieling", "Liaoyang", "Yingkou", "Fuxin", "Chaoyang", "Jinzhou", "Dandong", "Anshan"});


Model.put ("Inner Mongolia", new string[]{"Hohhot", "Hulunbeier", "Xilin Hot", "Baotou", "Chifeng", "Hailaer", "Wuhai", "Ordos", "Tongliao"});


Model.put ("Hebei", New string[]{"Shijiazhuang", "Tangshan", "Zhangjiakou", "Langfang", "Xingtai", "Handan", "Cangzhou", "Hengshui", "Chengde", "Baoding", "Qinhuangdao"});


Model.put ("Henan", New string[]{"Zhengzhou", "Kaifeng", "Luoyang", "Mesa", "Jiaozuo", "Hebi", "Xinxiang", "Anyang", "Puyang", "Xuchang", "Luohe", "Sanmenxia", "Nanyang", "Shangqiu", "Xinyang", "Zhoukou", " Zhumadian "});


Model.put ("Shandong", New string[]{"Jinan", "Qingdao", "Zibo," Weihai "," Qufu "," Linyi "," Yantai "," Zaozhuang "," Liaocheng "," Jining "," Heze "," Taian "," Rizhao "," dongying "," Dezhou "," Binzhou "," Laiwu "," Weifang "});


Model.put ("Shanxi", New string[]{"Taiyuan", "Yangquan", "Jincheng", "Jinzhong", "Linfen", "Yuncheng", "Changzhi", "Shuozhou", "Xinzhou", "Datong", "Luliang"});


Model.put ("Jiangsu", New string[]{"Nanjing", "Suzhou", "Kunshan," Nantong "," Taicang "," Wu County "," Xuzhou "," Yixing "," Zhenjiang "," Huaian "," Changshu "," Yancheng "," Taizhou "," Wuxi "," Lianyungang "," Yangzhou "," Changzhou "," Suqian "});


Model.put ("Anhui", New string[]{"Hefei", "Chaohu", "Bengbu," Anqing "," Liu'an "," Chuzhou "," Ma On Shan "," Fuyang "," Xuancheng "," Tongling "," Huaibei "," Wuhu "," Bozhou "," Suzhou "," Huainan "," Chizhou "});


Model.put ("Shaanxi", New string[]{"Xi ' an", "Hancheng", "Ankang", "Hanzhong", "Baoji", "Xianyang", "Yulin", "Weinan", "Shangluo", "Tongchuan", "Yanan"});


Model.put ("Ningxia", New string[]{"Yinchuan", "Guyuan", "Zhongwei", "Shizuishan", "Wuzhong"});


Model.put ("Gansu", New string[]{"Lanzhou", "Silver", "Qingyang", "Jiuquan", "Tianshui", "Wuwei", "Zhangye", "Gannan", "Linxia", "Pingliang", "Dingxi", "Jinchang"});


Model.put ("Qinghai", New string[]{"Xining", "Sea North", "Hercynian", "Huangnan", "Fruit Luo", "Yushu", "Haidong", "Hainan"});


Model.put ("Hubei", New string[]{"Wuhan", "Yichang," Huanggang "," Enshi "," Jingzhou "," Shennongjia "," Shiyan "," Xianning "," Xiangfan "," Xiaogan "," Suizhou "," Yellowstone "," Jingmen "," Ezhou "});


Model.put ("Hunan", New string[]{"Changsha", "Shaoyang", "Changde", "Chenzhou", "Jishou", "Zhuzhou", "Loudi", "Xiangtan", "Yiyang", "Yongzhou", "Yueyang", "Hengyang", "Huaihua", "Shaoshan", "Zhangjiajie"});


Model.put ("Zhejiang", New string[]{"Hangzhou", "Huzhou", "Jinhua", "Ningbo", "Lishui", "Shaoxing", "Yandang Mountain", "Quzhou", "Jiaxing", "Taizhou", "Zhoushan", "Wenzhou"});


Model.put ("Jiangxi", New string[]{"Nanchang", "Pingxiang", "Jiujiang", "Shangrao", "Fuzhou", "Ji", "Yingtan", "Yichun", "Xinyu", "Jingdezhen", "Ganzhou"});


Model.put ("Fujian", New string[]{"Fuzhou", "Xiamen", "Longyan", "Nanping", "Ningde", "Putian", "Quanzhou", "sanming", "Zhangzhou"});


Model.put ("Guizhou", New string[]{"Guiyang", "Anshun", "Chishui", "Zunyi", "Tongren", "Liupanshui", "Bijie", "Carey", "Duyun"});


Model.put ("Sichuan", New string[]{"Chengdu", "Luzhou", "Neijiang," Liangshan "," Aba "," Bazhong "," Guangyuan "," Leshan "," Mianyang "," Deyang "," Panzhihua "," Yaan "," Yibin "," Zigong "," Ganzi State "," Dazhou "," Ziyang "," Guang ' an "," Suining "," Meishan "," Nanchong "});


Model.put ("Guangdong", New string[]{"Guangzhou", "Shenzhen", "Chaozhou," Shaoguan "," Zhanjiang "," Huizhou "," Qingyuan "," Dongguan "," Jiangmen "," Maoming "," Zhaoqing "," Shanwei "," Heyuan "," Jieyang "," Meizhou "," Zhongshan "," Dechen "," Yangjiang "," Yunfu "," Zhuhai "," Shantou "," Foshan "});


Model.put ("Guangxi", New string[]{"Nanning", "Guilin", "Yangshuo," Liuzhou "," Wuzhou "," Yulin "," guiping "," Hezhou "," Qinzhou "," Guigang "," Fangchenggang "," Baise "," Beihai "," Hechi "," Guest "," Chongzuo "});


Model.put ("Yunnan", New string[]{"Kunming", "Baoshan," Chuxiong "," Dehong "," Red River "," Lincang "," Nu River "," Qujing "," Simao "," Wenshan "," Yuxi "," Zhaotong "," Lijiang "," Dali "});


Model.put ("Hainan", New string[]{"Haikou", "Sanya", "Zhanzhou", "Qiongshan", "Tong", "Wenchang"});


Model.put ("Xinjiang"), new string[]{"Urumqi", "Altay", "Aksu", "Changji", "Hami", "Hotan", "Kashi", "Karamay", "Shihezi", "Tacheng", "Korla", "Turpan", "Yining"});


}


}


2. Defines a method for acquiring a province, creates a map collection, assigns the mapping set obtained in the previous step to it, and uses the keyset () method of the map collection to get a set set of all the key objects in the collection, that is, a provincial collection that creates an object-type one-dimensional array. Converts the set collection to an array using the ToArray () method of the set interface, returning the array as a parameter to the province's Select Drop-down list.

3. Use the Setmodel () method of the JComboBox class to add province information to the province Drop-down list, which is the acquisition province method in the previous step.

4. Define the method of obtaining a city/county according to the province, create a map collection, assign the collection of mappings obtained in step 1 to it, and use the Get () method of the map collection to get the value of the specified key, that is, to create a string[-one-dimensional array for the city collection, and assign the city collection to the array.

5. Define the option state change event for the province Drop-down list, in which the selected province is obtained by the GetSelectedItem () method of the JComboBox class, by default to the first value in the Province collection, and then by using the removeallitems of the JComboBox class () Method clears the city list, obtains the city array according to the selected province, and then jcombobox the value of the city list by using the Setmodel () method of the.

The code is as follows:

Backgroundpanel.java

Copy Code code as follows:



Import Java.awt.Graphics;


Import Java.awt.Image;





Import Javax.swing.JPanel;





/**


* Panel component with background


*


* @author Zhongwei Lee


*/


public class Backgroundpanel extends JPanel {





/**


*


*/


Private static final long serialversionuid = 7758689434195492602L;


/**


* Background picture


*/


private image Image;





/**


* Construction Method


*/


Public Backgroundpanel () {


Super ();


Setopaque (FALSE);


SetLayout (NULL);


}





/**


* How to set up a picture


*/


public void setimage (image image) {


This.image = image;


}





@Override


protected void Paintcomponent (Graphics g) {//overriding drawing component appearance


if (image!= null) {


int width = getwidth ();//Get component Size


int height = getheight ();


G.drawimage (image, 0, 0, width, height, this);//Drawing picture is the same size as the assembly


}


Super.paintcomponent (g);//Executing superclass method


}


}


Swingresourcemanager.java

Copy Code code as follows:



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 such as colors, fonts, images, etc.


*


* This class may is freely distributed as part of the 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 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 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 specified path


* @param path String The path to the image file


* @return Image The image stored in the specified path


*/


public static Image GetImage (String path) {


Return GetImage ("default", path); $NON-nls-1$


}





/**


* Returns an image stored in 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 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


* @param section of 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 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 specified path


*/


public static ImageIcon GetIcon (class<?> clazz, String path) {


Return GetIcon (GetImage (clazz, Path));


}





/**


* Returns an icon stored in the specified path


* @param path String The path to the icon file


* @return icon The icon stored in the specified path


*/


public static ImageIcon GetIcon (String path) {


Return GetIcon ("default", path); $NON-nls-1$


}





/**


* Returns an icon stored in 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 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

Copy Code code as follows:



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


Get the default city


String province= (String) getprovince () [0];


Settitle ("input designated province/municipality query corresponding city and county");





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, "residence", 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) {//Option state Change Event


ItemChange ();


}


});


Combobox.setmodel (New DefaultComboBoxModel (Getprovince ())); Add province information





Final JLabel label = new JLabel ();


Label.settext ("province/municipality");


Label.setbounds (155, 30, 66, 18);


Panel.add (label);





Final JLabel label_1 = new JLabel ();


Label_1.settext ("City/County");


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 ("Name:");





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 ("Sex:");





Combobox_1 = new JComboBox ();


Combobox_1.setbounds (113, 81, 66, 25);


Backgroundpanel.add (combobox_1);


Combobox_1.setmodel (New DefaultComboBoxModel (new string[] {"Male", "female"});





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 ("Detailed Address:");





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 ("Save");





Final JButton button_1 = new JButton ();


Button_1.setbounds (265, 289, 75, 28);


Backgroundpanel.add (button_1);


Button_1.settext ("reset");


//


}





/**


* Access to provinces, municipalities, autonomous regions


*


* @return


*/


Public object[] Getprovince () {


map<string, string[]> map = citymap.model;//Get province info save to map


set<string> set = Map.keyset (); Gets the key in the Map collection and returns it with the Set collection


object[] province = Set.toarray (); Converting to arrays


return province; Returns the acquired province information


}





/**


* Get the city that corresponds to the specified province


*


* @param selectprovince


* @return


*/


Public string[] Getcity (String selectprovince) {


map<string, string[]> map = Citymap.model; Get province information to save in map


string[] arrcity = Map.get (selectprovince); Gets the value of the specified key


return arrcity; Return to acquired city


}





private void ItemChange () {


String selectprovince = (string) combobox.getselecteditem ();


Citycombobox.removeallitems (); Clear City/County list


string[] arrcity = getcity (selectprovince); Get City/County


Citycombobox.setmodel (New DefaultComboBoxModel (arrcity)); Re-add the value of the list of cities/counties


}





}


Effect as shown:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.