swing·通讯录项目预备知识之JTree__数据库构建节点树[二]
上篇本来就算是结束JTree的,但今天考虑到通讯录项目的体验效果,还是没忍住稍微深研究了一点。。。
今天要让初始话JTree的时候,从数据库读取子节点,形成每一个组别各有一个叶子节点的初始化状态
看数据库
然后是NodeDao.java
1 package com.java1234.dao;
2
3 import java.sql.Connection;
4 import java.sql.PreparedStatement;
5 import java.sql.ResultSet;
6 import java.sql.SQLException;
7
8 import com.java1234.model.Group;
9
10 public class NodeDao {
11 public ResultSet initData(Connection conn) throws Exception{
12 String sql = "select * from list_group";
13 PreparedStatement pst = conn.prepareStatement(sql);
14 ResultSet rs = pst.executeQuery();
15 return rs;
16 }
17 public ResultSet initChild(Connection conn, Group group) throws Exception{
18 StringBuffer sql = new StringBuffer("select * from link_man m,list_group g where m.groupId = g.id");
19 sql.append(" and g.groupName = '" + group.getGroupName() + "'");
20 PreparedStatement pst = conn.prepareStatement(sql.toString());
21
22 return pst.executeQuery();
23 }
24 }
Group.java
1 package com.java1234.model;
2
3 public class Group {
4 int id;
5 String groupName;
6
7 public Group() {
8 super();
9 // TODO Auto-generated constructor stub
10 }
11 public int getId() {
12 return id;
13 }
14 public void setId(int id) {
15 this.id = id;
16 }
17 public String getGroupName() {
18 return groupName;
19 }
20 public void setGroupName(String groupName) {
21 this.groupName = groupName;
22 }
23 public Group(String groupName) {
24 super();
25 this.groupName = groupName;
26 }
27
28 }
主界面类initTree方法更改为
1 private void initTree() {
2 Connection conn = null;
3 try {
4 conn = dbUtil.getCon();
5 ResultSet rs = nodeDao.initData(conn);
6 while (rs.next()) {
7 String groupName = rs.getString("groupName");
8 Group newGroup = new Group(groupName);
9 ResultSet rst = nodeDao.initChild(conn, newGroup);
10 DefaultMutableTreeNode newChild = new DefaultMutableTreeNode(groupName);
11 DefaultTreeModel model = (DefaultTreeModel) jtree_group.getModel();
12 while(rst.next()){
13 newSon = new DefaultMutableTreeNode(rst.getString("linkManName"));
14 newChild.add(newSon);
15 }
16 rootNode.add(newChild);
17 model.nodeStructureChanged(rootNode);
18 }
19 } catch (Exception e) {
20 // TODO Auto-generated catch block
21 JOptionPane.showMessageDialog(null, "初始化失败");
22 e.printStackTrace();
23 System.exit(0);
24 } finally {
25 try {
26 dbUtil.conClose(conn);
27 } catch (Exception e) {
28 // TODO Auto-generated catch block
29 e.printStackTrace();
30 }
31 }
32 }
效果图
这回就真的是终章了。。。。。到此为止
欢迎光临我师傅小锋哥的网站 Java知识分享网 www.java1234.com 有大量Java资料供学习参考用,一切免费