Java implements the Map collection secondary linkage example

  • 2020-04-01 03:02:17
  • OfStack

Map collections can save the key value mapping relationship, which is very suitable for this example the required data structures, information can be stored for all provinces Map collections of keys, and the information can be stored for each key corresponding to the city, this example is to use the Map collection implements the provincial selection box, when choosing province information, will change the city the drop-down selection box corresponding content.

Thought analysis:

1. Create a nationwide (province, municipality, autonomous region) mapping set, that is, a LinkedHashMap object, and use the put () method of the Map interface to add the specified mapping relationship between province and city to the set, where the value is a String one-dimensional array.

The code is as follows:

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(" 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 river "," That is suihua "," Greater hinggan mountains "});
        model.put(" Ji Lin ", new String[]{" changchun "," yanbian "," Ji Lin "," baishan "," baicheng "," siping "," matsubara "," long-withering "," Dan an "," tonghua "});
        model.put(" liaoning ", new String[]{" shenyang "," dalian "," huludao "," lushun "," benxi "," fushun "," tieling "," liaoyang "," yingkou "," fuxin "," The rising sun "," jinzhou "," dandong "," anshan "});
        model.put(" Inner Mongolia ", new String[]{" Hohhot, "," The hulunbuir "," Tin event, "," baotou "," chifeng "," hailar "," The wuhai "," ordos "," tgo "});
        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 "," Luo river "," 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 "," Texas "," binzhou "," laiwu "," weifang "});
        model.put(" shanxi ", new String[]{" taiyuan "," yangquan "," jincheng "," jinzhong "," linfen "," yuncheng "," changzhi "," It is mined here "," 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 lake "," bengbu "," anqing "," luan "," chuzhou "," Ma on shan "," fuyang "," xuancheng "," tongling "," huaibei "," wuhu "," Nano state "," suzhou "," huainan "," chizhou "});
        model.put(" shaanxi ", new String[]{" Xi 'an "," Seoul "," ankang "," Hanzhong city "," baoji "," xianyang "," Yulin. "," weinan "," shangluo "," tongchuan "," yanan "});
        model.put(" ningxia ", new String[]{" yinchuan "," evalution "," Central defender "," making "," hui "});
        model.put(" gansu ", new String[]{" lanzhou "," silver "," qingyang "," jiuquan "," tianshui "," wuwei "," Zhang ye "," gannan "," linxia "," Of out "," dingxi "," jinchang "});
        model.put(" qinghai ", new String[]{" xining "," Distance from the north sea "," hercynian "," prefecture "," Go luo "," yushu "," Whereas haidong539 "," 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 "," Which is "," 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 "," gian "," yingtan "," yichun "," at "," 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 "," DouYun "});
        model.put(" sichuan ", new String[]{" chengdu "," luzhou "," neijiang "," liangshan "," aba "," pakistan-china "," guangyuan "," leshan "," mianyang "," deyang "," panzhihua "," ya "," yibin "," zigong "," T he "," dazhou "," great "," cross "," 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 "," GuiPing "," Congratulation state "," qinzhou "," Your port "," fangchenggang "," The baise "," The north sea "," hechi "," The guest "," The left part "});
        model.put(" yunnan ", new String[]{" kunming "," baoshan "," chuxiong "," dehong "," The red river "," lincang "," nu "," qujing "," simao "," wenshan "," yuxi "," zhaotong "," lijiang "," Dali "});
        model.put(" hainan ", new String[]{" haikou "," sanya "," danzhou "," QiongShan "," TongShen "," wenchang "});
        model.put(" xinjiang ", new String[]{" urumqi "," altay "," aksu "," changji "," hami "," hetian "," kashgar "," karamay "," shihezi "," Tacheng prefecture "," korla "," turpan "," yining "});
    }
}

2. The definition method for provinces, to create a Map collections, the mapping Set will step on to get assigned to it, use the Map collections keySet () method to obtain the Set of all the key Object in the collection collection, collection is the provinces, to create a one dimensional array Object type, using the Set interface toArray () method converts the Set Set to array, returns the array as provinces to choose the parameters of the drop-down list.

3. Use the setModel() method of the JComboBox class to add the province information to the province drop-down list, and the parameter is the province method obtained in the previous step.

4. According to the method of getting cities/counties by province, create a Map set, assign the Map set obtained in step 1 to it, use the get() method of Map set to get the value of the specified key, that is, the city/county set, create a String[] one-dimensional array, and assign the city/county set to the array.

5. Define the province a drop-down list of options state change events, in the event by getSelectedItem JComboBox class () method to obtain the selected provinces, the default for the province the first of a set of values, and then use the removeAllItems JComboBox class list () method to empty city/county, according to the selected provinces city/county array, finally using JComboBox setModel () method to add the value of the city/county list.

      The code is as follows:

BackgroundPanel. Java


import java.awt.Graphics;
import java.awt.Image;

import javax.swing.JPanel;


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) {//Overrides the rendering component appearance
        if (image != null) {
            int width = getWidth();//Get the component size
            int height = getHeight();
            g.drawImage(image, 0, 0, width, height, this);//Drawing a picture is the same size as the component
        }
        super.paintComponent(g);//Execute the superclass method
    }
}

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;


public class SwingResourceManager {

    
    private static HashMap<String, Image> m_ClassImageMap = new HashMap<String, Image>();

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

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

    
    public static Image getImage(String path) {
        return getImage("default", path); //$NON-NLS-1$
    }

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

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

    
    public static ImageIcon getIcon(Class<?> clazz, String path) {
        return getIcon(getImage(clazz, path));
    }

    
    public static ImageIcon getIcon(String path) {
        return getIcon("default", path); //$NON-NLS-1$
    }

    
    public static ImageIcon getIcon(String section, String path) {
        return getIcon(getImage(section, path));
    }

    
    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;

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

    
    public MainFrame() {
        getContentPane().setLayout(null);
        setBounds(100, 100, 518, 379);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //Gets the default city/county
        String province=(String)getProvince()[0];
        setTitle(" Input specified province / The municipality queries the 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, " To live ", 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 events
                itemChange();
            }
        });
        comboBox.setModel(new DefaultComboBoxModel(getProvince())); //Add province information

        final JLabel label = new JLabel();
        label.setText(" province / Municipalities directly under the central government ");
        label.setBounds(155, 30, 66, 18);
        panel.add(label);

        final JLabel label_1 = new JLabel();
        label_1.setText(" The 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(" The surname      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      Don't: ");

        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 ");
        //
    }

    
    public Object[] getProvince() {
        Map<String, String[]> map = CityMap.model;//Get the province information and save it in a Map
        Set<String> set = map.keySet(); //Gets the key in the Map collection and returns as a Set Set
        Object[] province = set.toArray(); //Convert to array
        return province; //Returns the retrieved province information
    }

    /**
     *  Gets the city corresponding to the specified province / county 
     * 
     * @param selectProvince
     * @return
     */
    public String[] getCity(String selectProvince) {
        Map<String, String[]> map = CityMap.model; //Get the province information and save it in a Map
        String[] arrCity = map.get(selectProvince); //Gets the value of the specified key
        return arrCity; //Returns the city/county obtained
    }

    private void itemChange() {
        String selectProvince = (String) comboBox.getSelectedItem();
        cityComboBox.removeAllItems(); //Empty the city/county list
        String[] arrCity = getCity(selectProvince); //Get city/county
        cityComboBox.setModel(new DefaultComboBoxModel(arrCity)); //Readd the value of the city/county list
    }

}

The effect is as follows:

< img border = 0 SRC = "/ / files.jb51.net/file_images/article/201403/201431153904263.png" >


Related articles: