最近在看“企业快信”的源代码,这个项目的好友列表是用JTree实现的。
在理解了它的写法之后,就想把JTree控件的使用熟悉一下。于是自己写了个小练习,就是显示数据库中的用户名和图片路径在JTree中,并且还可以添加用户,同时在JTree中显示。
JTree中,有TreeCellRenderer接口,可以用类来实现这个接口。在这个接口相应的方法中,可以对树中的节点进行设置。如我就是在这个方法中设置节点的大小,以及判断节点,然后将节点用一定的样式显示。
然后,再可以写一个类,继承至JTree,为它设置根节点DefaultMutableTreeNode root和DefaultTreeModel treeModel。然后设置它的setCellRenderer为刚才写的继承TreeCellRenderer的类。那么就可以添加节点,用root.add(new DefaultMutableTreeNode(**))方法,和root.remove()方法来移除节点。值得注意的是,setModel必需在setCellRenderer之后,而且,jpanel设为GridLayout(1,1)后再add JTree。
连接数据库的方法:
package com.lzw.dao; import java.sql.*; import com.lzw.User.User1; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Administrator */ public class Dao { public static Connection getConnection() { Connection conn=null; try { String driver="com.microsoft.jdbc.sqlserver.SQLServerDriver"; String url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=test"; String username="sa"; String pwd="sa"; Class.forName(driver); conn=DriverManager.getConnection(url,username,pwd); } catch(Exception ex) { System.out.println(ex.getMessage()); } return conn; } public static void addUser(User1 user) { String sql="insert into user1 values(?,?)"; PreparedStatement pstm=null; Connection conn=getConnection(); try { pstm=conn.prepareStatement(sql); pstm.setString(1, user.getUsername()); pstm.setString(2, user.getImageurl()); pstm.execute(); } catch(Exception ex) { ex.printStackTrace(); } finally { try { pstm.close(); } catch (SQLException ex) { Logger.getLogger(Dao.class.getName()).log(Level.SEVERE, null, ex); } try { conn.close(); } catch (SQLException ex) { Logger.getLogger(Dao.class.getName()).log(Level.SEVERE, null, ex); } } } public static void delUser(User1 user) { String sql="delete user1 where username=?"; PreparedStatement pstm=null; Connection conn=getConnection(); try { pstm=conn.prepareStatement(sql); pstm.setString(1, user.getUsername()); pstm.executeUpdate(); } catch(Exception ex) { ex.printStackTrace(); } finally { try { pstm.close(); } catch (SQLException ex) { Logger.getLogger(Dao.class.getName()).log(Level.SEVERE, null, ex); } try { conn.close(); } catch (SQLException ex) { Logger.getLogger(Dao.class.getName()).log(Level.SEVERE, null, ex); } } } public static ArrayList
User1表对应的类:
package com.lzw.User; /** * * @author Administrator */ public class User1 { String username; String imageurl; public void setUsername(String name) { this.username=name; } public void setImageurl(String url) { this.imageurl=url; } public String getUsername() { return this.username; } public String getImageurl() { return this.imageurl; } }
UserRenderer类:
package com.lzw.User; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreeCellRenderer; /** * * @author Administrator */ public class UserRenderer extends JPanel implements TreeCellRenderer { private User1 user=null; private JLabel jb_username=new JLabel(); private JLabel jb_imageurl=new JLabel(); public UserRenderer() { super(); user=null; } public UserRenderer(Icon open,Icon close,Icon leaf) { super(); this.setLayout(new BorderLayout()); } public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { if(value instanceof DefaultMutableTreeNode) { DefaultMutableTreeNode dt=(DefaultMutableTreeNode)value; Object oo=dt.getUserObject(); if(oo instanceof User1) { user=(User1)oo; } } else if(value instanceof User1) { user=(User1)value; } if(user!=null) { // System.out.println(user.getUsername()); jb_username.setText(user.getUsername()); jb_imageurl.setText(user.getImageurl()); add(jb_username,BorderLayout.WEST); add(jb_imageurl,BorderLayout.CENTER); this.setPreferredSize(new Dimension(380,20)); } return this; } }
UserTree类:
package com.lzw.User; import com.lzw.dao.Dao; import java.awt.*; import java.awt.event.*; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.*; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.MutableTreeNode; import javax.swing.tree.TreePath; /** * * @author Administrator */ public class UserTree extends JTree{ DefaultMutableTreeNode root; DefaultTreeModel treeModel; public UserTree() { root=new DefaultMutableTreeNode("root"); treeModel=new DefaultTreeModel(root); this.setRowHeight(20); // this.setModel(treeModel); this.setToggleClickCount(2); this.setRootVisible(false); DefaultTreeCellRenderer my=new DefaultTreeCellRenderer(); UserRenderer userRender=new UserRenderer(my.getOpenIcon(),my.getClosedIcon(),my.getLeafIcon()); this.setCellRenderer(userRender); this.setModel(treeModel); sortUsers(); } public synchronized void sortUsers() { new Thread(new Runnable(){ public void run(){ try { Thread.sleep(100); ArrayList
界面:
package com.lzw.frame; import com.lzw.User.User1; import com.lzw.User.UserTree; import java.awt.GridLayout; /** * * @author Administrator */ public class MainFrame extends javax.swing.JFrame { private UserTree mytree; /** Creates new form MainFrame */ public MainFrame() { initComponents(); mytree=new UserTree(); this.jPanel1.setLayout(new GridLayout(1,1)); this.jPanel1.add(mytree); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") //