Map sets can save key-value mapping relationships, which is very suitable for the data structures required in this example. All province information can be saved as keys of the Map set, and each key can save the corresponding city information. This example is implemented using Map sets. The provincial and municipal cascade selection box will change the corresponding content of the city drop-down selection box when selecting province information.
Idea Analysis:
1. Create a national (province, municipality, autonomous region) mapping set, that is, a LinkedHashMap object. Use the put() method of the Map interface to add the mapping relationship between the specified province and the city to the collection, where the value is a String-type one-dimensional array.
The code is as follows:
CityMap.java
The code copy is as follows:
import java.util.LinkedHashMap;
import java.util.Map;
public class CityMap {
/**
* National (province, municipality, autonomous region) mapping collection
*/
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","Baishan","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","Hulunbuir","Xilinhot","Baotou","Chipong","Hailar","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","Pingdingshan","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", "Tai'an", "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","Wuxian","Xuzhou","Yixing","Zhenjiang"," Huaian", "Changshu", "Yancheng", "Taizhou", "Wuxi", "Lianyungang", "Yangzhou", "Changzhou", "Suqian"});
model.put("Anhui", new String[]{"Hefei","Chaohu","Bengbu","Anqing","Lu'an","Chuzhou","Ma'anshan","Fuyang","Xuancheng" ,"Tongling","Huaibei","Wuhu","Haozhou","Suzhou","Huainan","Chizhou"});
model.put("Shaanxi", new String[]{"Xi'an","Hancheng","Ankang","Hanzhong","Baoji","Xianyang","Yulin","Weinan","Shangluo", "Tongchuan", "Yan'an"});
model.put("Ningxia", new String[]{"Yinchuan","Guyuan","Zhongwei","Shizuishan","Wuzhong"});
model.put("Gansu", new String[]{"Lanzhou","Baiyin","Qingyang","Jiuquan","Tianshui","Wuwei","Zhangye","Gannan","Linxia", "Pingliang", "Dingxi", "Jinchang"});
model.put("Qinghai", new String[]{"Xining","Haibei","Haixi","Huangnan","Goluo","Yushu","Haidong","Hainan"}) ;
model.put("Hubei", new String[]{"Wuhan","Yichang","Huanggang","Enshi","Jingzhou","Shennongjia","Shiyan","Xianning","Xiangfan"," Xiaogan", "Suizhou", "Huangshi", "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","Yandangshan","Quzhou","Jiaxing", "Taizhou", "Zhoushan", "Wenzhou"});
model.put("Jiangxi", new String[]{"Nanchang","Pingxiang","Jiujiang","Shangrao","Fuzhou","Ji'an","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","Kaili","Duyun" });
model.put("Sichuan", new String[]{"Chengdu","Luzhou","Neijiang","Liangshan","Aba","Bazhong","Guangyuan","Leshan","Mianyang", "Deyang", "Panzhihua", "Ya'an", "Yibin", "Zigong", "Ganzizhou", "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", "Deqing", "Yangjiang", "Yunfu", "Zhuhai", "Shantou", "Foshan "});
model.put("Guangxi", new String[]{"Nanning","Guilin","Yangshuo","Liuzhou","Wuzhou","Yulin","Guiling","Hezhou","Qinzhou"," Guigang", "Fangchenggang", "Baise", "Beihai", "Hechi", "Laibin", "Chongzuo"});
model.put("Yunnan", new String[]{"Kunming","Baoshan","Chuxiong","Dehong","Honghe","Lincang","Nujiang","Qujing","Simao" ,"Wenshan","Yuxi","Zhaotong","Lijiang","Dali"});
model.put("Hainan", new String[]{"Haikou","Sanya","Danzhou","Qiongshan","Tongshi","Wenchang"});
model.put("Xinjiang", new String[]{"Urumqi","Altay","Aksu","Changji","Hami","Hotan","Kashgar","Karamay","Shihezi"," Tacheng", "Korla", "Turpan", "Yining"});
}
}
2. Define the method to obtain the province, create a Map collection, assign the map collection obtained in the previous step to it, and use the keySet() method of the Map collection to obtain the Set set composed of all key objects in the collection, that is, the province collection , create an Object-type one-dimensional array, use the toArray() method of the Set interface to convert the Set collection into an array, and return this array as a parameter for the province selection drop-down list.
3. Use the setModel() method of the JComboBox class to add province information to the province drop-down list, and the parameters are the method of obtaining provinces in the previous step.
4. Define the method of obtaining cities/counties according to the province, create a Map collection, assign the map collection 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, the city/county collection. Create a String[] type one-dimensional array and assign city/county collection to the array.
5. Define the option status change event of the province drop-down list. In this event, the selected province is obtained through the getSelectedItem() method of the JComboBox class. The default is the first value in the province collection. Then use the removeAllItems() method of the JComboBox class to clear it. City/county list, obtain the city/county array according to the selected province, and finally use the setModel() method of JComboBox to re-add the value of the city/county list.
The code is as follows:
BackgroundPanel.java
The code copy is as follows:
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.JPanel;
/**
* Panel assembly with background
*
* @author ZhongWei Lee
*/
public class BackgroundPanel extends JPanel {
/**
*
*/
private static final long serialVersionUID = 7758689434195492602L;
/**
* Background picture
*/
private Image image;
/**
* Constructing method
*/
public BackgroundPanel() {
super();
setOpaque(false);
setLayout(null);
}
/**
* How to set pictures
*/
public void setImage(Image image) {
this.image = image;
}
@Override
protected void paintComponent(Graphics g) {// Rewrite the appearance of the drawing component
if (image != null) {
int width = getWidth();// Get component size
int height = getHeight();
g.drawImage(image, 0, 0, width, height, this);// Drawing the image is the same as the component size
}
super.paintComponent(g);// Execute superclass method
}
}
SwingResourceManager.java
The code copy is 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 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
The code copy is 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/county
String province=(String)getProvince()[0];
setTitle("Enter the corresponding city and county to query the designated province/municipality");
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, "place of 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 status change event
itemChange();
}
});
comboBox.setModel(new DefaultComboBoxModel(getProvince())); // Add province information
final JLabel label = new JLabel();
label.setText("Province/Metropolis");
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("Gender:");
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");
//
}
/**
* Obtain provinces, municipalities, autonomous regions
*
* @return
*/
public Object[] getProvince() {
Map<String, String[]> map = CityMap.model;// Get province information and save it to the map
Set<String> set = map.keySet(); // Get the key in the Map collection and return it as the Set collection
Object[] province = set.toArray(); // Convert to array
return province; // Return the obtained province information
}
/**
* Get the city/county corresponding to the designated province
*
* @param selectProvince
* @return
*/
public String[] getCity(String selectProvince) {
Map<String, String[]> map = CityMap.model; // Get province information and save it to the map
String[] arrCity = map.get(selectProvince); // Get the value of the specified key
return arrCity; // Return to the obtained city/county
}
private void itemChange() {
String selectProvince = (String) comboBox.getSelectedItem();
cityComboBox.removeAllItems(); // Clear the city/county list
String[] arrCity = getCity(selectProvince); // Get city/county
cityComboBox.setModel(new DefaultComboBoxModel(arrCity)); // Re-add the value of the city/county list
}
}
The effect is shown in the picture: