提供有china.xml和china.sql文件,实现全国省市区的三级联动效果

一、xml实现

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JComboBox;
import javax.swing.JLabel;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import java.awt.Font;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.swing.DefaultComboBoxModel;

@SuppressWarnings("serial")
public class ChinaJFrame extends JFrame {

private JPanel contentPane;
    private List<String> cityList=null;
    private List<String> provinceList=null;
    private List<String> countyList=null;
    @SuppressWarnings("rawtypes")
    private JComboBox provinceComboBox, cityComboBox, countyComboBox;
    SAXReader reader = new SAXReader();
    Document document = null;
    List<String> list=null;
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    ChinaJFrame frame = new ChinaJFrame();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    /**
     * Create the frame.
     *
     * @throws DocumentException
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public ChinaJFrame() throws DocumentException {
        setResizable(false);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

provinceComboBox = new JComboBox();
        provinceComboBox.setModel(new DefaultComboBoxModel(new String[] { "省份" }));
        provinceComboBox.setBounds(33, 106, 108, 21);
        
        cityComboBox = new JComboBox();
        cityComboBox.setBounds(171, 106, 108, 21);
        cityComboBox.setModel(new DefaultComboBoxModel(new String[] { "地级市" }));
        
        countyComboBox = new JComboBox();
        countyComboBox.setBounds(302, 106, 108, 21);
        countyComboBox.setModel(new DefaultComboBoxModel(new String[] { "市、县级市" }));
        
        
        provinceList = getProvince("province");
        for (String s : provinceList) {
            provinceComboBox.addItem(s);
        }
        
        provinceComboBox.addItemListener(new ItemListener() {

@Override
            public void itemStateChanged(ItemEvent e) {
                if(e.getStateChange() == ItemEvent.SELECTED){
                    int ProvinceIndex = provinceComboBox.getSelectedIndex();
                    cityList = getCity(ProvinceIndex);    
                    cityComboBox.removeAllItems();
                    for (String s : cityList) {
                        cityComboBox.addItem(s);
                    }
                }
            }
        });
        
        cityComboBox.addItemListener(new ItemListener() {
            
            @Override
            public void itemStateChanged(ItemEvent e) {
                
                if(e.getStateChange() == ItemEvent.SELECTED){
                    cityComboBox=(JComboBox) e.getSource();
                    String name2=(String) cityComboBox.getSelectedItem();
                    countyList=getCounty(name2);
                    
                    countyComboBox.removeAllItems();
                    for(String cl:countyList){
                        countyComboBox.addItem(cl);
                    }
                }
                
            }
        });
        
        JLabel lblNewLabel = new JLabel(
                "\u5168\u56FD\u57CE\u5E02\u4E09\u7EA7\u8054\u52A8");
        lblNewLabel.setFont(new Font("宋体", Font.BOLD, 18));
        lblNewLabel.setBounds(140, 25, 160, 48);

contentPane.add(provinceComboBox);
        contentPane.add(cityComboBox);
        contentPane.add(countyComboBox);
        contentPane.add(lblNewLabel);
    }

@SuppressWarnings("unchecked")
    public List<String> getProvince(String name) {
        list = new ArrayList<String>();
        try {
            document = reader.read(new File("src/china.xml"));
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        Element root = document.getRootElement();
        for(Iterator<Element> i = root.elementIterator(name); i.hasNext();) {
            Element node = i.next();
            List<Attribute> attrs = node.attributes();
            if (attrs != null) {
                for (Attribute attr : attrs) {
                    list.add(attr.getValue());
                }
            }
        }
        return list;
    }

@SuppressWarnings("unchecked")
    public List<String> getCity(int index) {
        list = new ArrayList<String>();
        try {
            document = reader.read(new File("src/china.xml"));
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        Element root = document.getRootElement();
        List<Element> elements = root.elements();
        List<Element> elements1 = elements.get(index-1).elements();
        for (int i=0; i < elements1.size(); i++) {
            List<Attribute> attrs = elements1.get(i).attributes();
            if (attrs != null) {
                for (Attribute attr : attrs) {
                    list.add(attr.getValue());
                }
            }
        }
        return list;

}

@SuppressWarnings("unchecked")
    public List<String> getCounty(String name2){
        list = new ArrayList<String>();
        
        try {
            document = reader.read(new File("src/china.xml"));
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        ////province[@name='北京市']
        List<Node> nodes = document.selectNodes("//city[@name='" + name2 + "']//county//@name");
        for (Node node : nodes) {
            list.add(node.getText());
        }
        return list;

}
}

二、数据库实现

(1)数据库连接的配置文件

<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
    <!-- 指定名称的配置 -->
    <named-config name="oa">
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/china</property>
        <property name="user">root</property>
        <property name="password">root</property>
        <property name="maxPoolSize">100</property>
        <property name="initialPoolSize">20</property>
        <property name="minPoolSize">10</property>
        <property name="acquireIncrement">5</property>
    </named-config>
    <!-- 缺省的配置 -->
    <default-config>
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/china</property>
        <property name="user">root</property>
        <property name="password">root</property>
        <property name="maxPoolSize">100</property>
        <property name="initialPoolSize">20</property>
        <property name="minPoolSize">10</property>
        <property name="acquireIncrement">5</property>
    </default-config>
</c3p0-config>

(2)实体Bean

public class Province {//省
    private Integer id;
    private String name;

}

public class City {//市
    private Integer id;
    private String name;
    private Integer p_id;

}

public class County {//区
    private Integer id;
    private String name;
    private Integer c_id;

}

(3)数据库操作接口定义和实现

public interface ChinaDao<T> {
    List<T> getObjects();
    List<T> getCityObjectsById(Integer id);
    List<T> getCountyObjectsById(Integer id);
    City getIdByName(String name);
}

public class ChinaDaoImpl<T> implements ChinaDao<T>{
    private JdbcTemplate jdbcTemplate=new JdbcTemplate(DBConn.getDataSourse());
    private List<T> entities=null;

@SuppressWarnings({ "unchecked", "rawtypes" })
    @Override
    public List<T> getObjects() {
        String sql="select id, name from province";
        entities=jdbcTemplate.query(sql, new RowMapper(){

@Override
            public Object mapRow(ResultSet rs, int arg1) throws SQLException {
                Province province=new Province();
                province.setId(rs.getInt("id"));
                province.setName(rs.getString("name"));
                return province;
            }
            
        });
        return entities;
    }
    
    @SuppressWarnings({ "unchecked", "rawtypes" })
    @Override
    public List<T> getCityObjectsById(Integer id) {
        String sql="select id, name ,p_id from city where p_id=?";
        entities=jdbcTemplate.query(sql, new Object[]{id},new RowMapper(){
            @Override
            public Object mapRow(ResultSet rs, int arg1) throws SQLException {
                City city=new City();
                city.setId(rs.getInt("id"));
                city.setName(rs.getString("name"));
                city.setP_id(rs.getInt("p_id"));
                return city;
            }
            
        });
        return entities;
    }

@SuppressWarnings({ "unchecked", "rawtypes" })
    @Override
    public List<T> getCountyObjectsById(Integer id) {
        String sql="select id, name ,c_id from county where c_id=?";
        entities=jdbcTemplate.query(sql, new Object[]{id},new RowMapper(){

@Override
            public Object mapRow(ResultSet rs, int arg1) throws SQLException {
                County county=new County();
                county.setId(rs.getInt("id"));
                county.setName(rs.getString("name"));
                county.setC_id(rs.getInt("c_id"));
                return county;
            }
            
        });
        return entities;
    }

@SuppressWarnings({ "unchecked", "rawtypes" })
    @Override
    public City getIdByName(String name) {
        String sql="select id, name ,p_id from city where name=?";
        City entity=jdbcTemplate.queryForObject(sql, new Object[]{name},new RowMapper(){
            @Override
            public Object mapRow(ResultSet rs, int arg1) throws SQLException {
                City city=new City();
                city.setId(rs.getInt("id"));
                city.setName(rs.getString("name"));
                city.setP_id(rs.getInt("p_id"));
                return city;
            }    
        });
        return entity;
    }
}

(4)具体实现

public class ChinaJFrame extends JFrame {
    private ChinaDao chinaDao=new ChinaDaoImpl();
    private JPanel contentPane;
    private List<String> cityList=null;
    private List<String> provinceList=null;
    private List<String> countyList=null;
    @SuppressWarnings("rawtypes")
    private JComboBox provinceComboBox, cityComboBox, countyComboBox;
    SAXReader reader = new SAXReader();
    Document document = null;
    List<String> list=null;
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    ChinaJFrame frame = new ChinaJFrame();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    /**
     * Create the frame.
     *
     * @throws DocumentException
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public ChinaJFrame() throws DocumentException {
        setResizable(false);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

provinceComboBox = new JComboBox();
        provinceComboBox.setModel(new DefaultComboBoxModel(new String[] { "省份" }));
        provinceComboBox.setBounds(33, 106, 108, 21);
        
        cityComboBox = new JComboBox();
        cityComboBox.setBounds(171, 106, 108, 21);
        cityComboBox.setModel(new DefaultComboBoxModel(new String[] { "地级市" }));
        
        countyComboBox = new JComboBox();
        countyComboBox.setBounds(302, 106, 108, 21);
        countyComboBox.setModel(new DefaultComboBoxModel(new String[] { "市、县级市" }));
        
        List<Province> provinces=chinaDao.getObjects();
        provinceList = new ArrayList<String>();
        for(Province p:provinces){
            provinceList.add(p.getName());
        }
        for (String s : provinceList) {
            provinceComboBox.addItem(s);
        }
        
        provinceComboBox.addItemListener(new ItemListener() {

@Override
            public void itemStateChanged(ItemEvent e) {
                if(e.getStateChange() == ItemEvent.SELECTED){
                    cityList=new ArrayList<String>();
                    int ProvinceIndex = provinceComboBox.getSelectedIndex();
                    
                    List<City> cities=chinaDao.getCityObjectsById(ProvinceIndex);
                    for(City city:cities){
                        cityList.add(city.getName());
                    }
                    
                    cityComboBox.removeAllItems();
                    for (String s : cityList) {
                        cityComboBox.addItem(s);
                    }
                }
            }
        });
        
        cityComboBox.addItemListener(new ItemListener() {
            
            @Override
            public void itemStateChanged(ItemEvent e) {        
                if(e.getStateChange() == ItemEvent.SELECTED){
                    cityComboBox=(JComboBox) e.getSource();
                    String name=(String) cityComboBox.getSelectedItem();
                    countyList=new ArrayList<String>();
                    int CityIndex = chinaDao.getIdByName(name).getId();
                    List<County> counties=chinaDao.getCountyObjectsById(CityIndex);
                    
                    for(County county:counties){
                        countyList.add(county.getName());
                    }
                    countyComboBox.removeAllItems();
                    for(String cl:countyList){
                        countyComboBox.addItem(cl);
                    }
                }
                
            }
        });
        
        JLabel lblNewLabel = new JLabel(
                "\u5168\u56FD\u57CE\u5E02\u4E09\u7EA7\u8054\u52A8");
        lblNewLabel.setFont(new Font("宋体", Font.BOLD, 18));
        lblNewLabel.setBounds(140, 25, 160, 48);

contentPane.add(provinceComboBox);
        contentPane.add(cityComboBox);
        contentPane.add(countyComboBox);
        contentPane.add(lblNewLabel);
    }
}

三级联动查询全国省市区(xml与数据库)的更多相关文章

  1. Ajax案例:三级联动查询员工的信息(三张表进行内连接)

    需求分析: 通过数据库连接池,可以查询到数据库中员工的各种信息,通过点击下拉框的方式实现三级联动,即:没有点击city下拉框,后面两个下拉框中没有值,这样,点击city下拉框,department下拉 ...

  2. JQuery中国省市区无刷新三级联动查询

    之前有写过用<Ajax控件来实现中国的省市区无刷新查询> 今天用JQuery来实现,用Ajax控件和JQuery的优缺点就先不说了. 效果图如下: 下面来结合代码来详细说明一下如何用JQu ...

  3. Ado.Net实现简易(省、市、县)三级联动查询,还附加Access数据

    小弟在博客园驻园不久,初来咋到:将最近写的小程序附上,希望各位大牛们吐槽:激发对程序员围观的童鞋们,赶紧加入IT行业,如果你在上海那简称就是SHIT,哈哈题外话,以下开始切入正题: 坐公交车是旁边偶遇 ...

  4. tp 5 三级联动查询(自写)

    思路: 1.定义路由 2.查询顶级分类(pid=0)发送至制图 3.循环展示 4.给顶级分类下拉框绑定内容改变事件(JS:onchange.JQ:change) 5.获取到选中的option的valu ...

  5. java map实现二级联动查询(省市区下拉列表查询)

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

  6. Mysql学习---全国省市区以及邮编数据库

    更多下载

  7. 在使用ajax实现三级联动调用数据库数据并通过调出的数据进行二级表单查询

    在使用ajax实现三级联动查询数据库数据后再使用ajax无刷新方式使用三级联动调出的数据进行二级查询 但是现在遇到问题,在二级查询的时候期望是将数据以表格的形式展示在三级联动的下方,但是现在在查询后会 ...

  8. ajax省市区三级联动

    jdbc+servlet+ajax开发省市区三级联动 技术点:jdbc操作数据库,ajax提交,字符拦截器,三级联动 特点:局部刷新达到省市区三级联动,举一反三可以做商品分类等 宗旨:从实战中学习 博 ...

  9. JS省市区三级联动

    不需要访问后台服务器端,不使用Ajax,无刷新,纯JS实现的省市区三级联动. 当省市区数据变动是只需调正js即可. 使用方法: <!DOCTYPE html><html>< ...

随机推荐

  1. java.lang.ExceptionInInitializerError

    java.lang.ExceptionInInitializerError at com.csdhsm.compiler.test.DevTest.testReadInput(DevTest.java ...

  2. navtab方法参数以及事件

    参数(options) DOM方式初始化navtab的,推荐使用集合属性data-options定义参数,如果使用data属性定义参数,注意转换成对应的名称. 名称 类型 默认值 描述 id stri ...

  3. python tuple 操作

    特点:不可改(与字符串一样.不允许删除和修改) 操作:1.print 可使用跟%的元祖  print( '%s is %d years old' % (name, age)) 2.像列表一样有索引 3 ...

  4. MapReduce实现TopK的示例

    由于开始学习MapReduce编程已经有一段时间了,作为一个从编程中寻找自信和乐趣以及热爱编程的孩子来讲,手开始变得很“痒”了,很想小试一下身手.于是自己编写了TopK的代码.TopK的意思就是从原文 ...

  5. hive 中 union all

    hive 中的union all是不能在sql语句的第一层使用的,否则会报 Top level UNION is not supported currently 错误: 例如如下的方式: select ...

  6. Eclipse卡死问题解决办法

    偶尔浏览到几个eclipse卡死的文章,收集一下. 1.  eclipse 3.6卡死 eclipse自动提示反应慢,或者卡死, 有人说这是eclipse 3.6的版本bug, 但是3.5版本好像也有 ...

  7. js 检测 flash插件以及版本号 通用所有浏览器

    var fls = flashChecker(); if (fls.h) { if (fls.v < parseFloat('8.0')) { alert("您当前的flash pla ...

  8. vi中的批量替换

    举个例子啊: 将文件tihuan(假设此文本中字符a)中的所有字符a换成字符w,其命令为: 1.vi tihuan 2.按esc键 3.按shift+: 4.在:后输入    %s/a/w/g 就ok ...

  9. JLOI 提示问题

    按照题目意思模拟即可. Program XJOI2265; ..] of char=('a','e','i','o','u','A','E','I','O','U'); var s:ansistrin ...

  10. C,C++宏中#与##的讲解[转]

    MoreWindows 专注于Windows编程 C,C++宏中#与##的讲解 文中__FILE__与示例1可以参见<使用ANSI C and Microsoft C++中常用的预定义宏> ...