JAVA中JTree的使用

最近在看“企业快信”的源代码,这个项目的好友列表是用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 getAllUser() { String sql="select * from user1"; ArrayList list=new ArrayList(); Connection conn=getConnection(); Statement stm=null; ResultSet rs=null; try { stm=conn.createStatement(); rs=stm.executeQuery(sql); while(rs.next()) { User1 user=new User1(); user.setUsername(rs.getString(2)); user.setImageurl(rs.getString(3)); list.add(user); } } catch(SQLException ex) { ex.printStackTrace(); } finally { try { rs.close(); } catch (SQLException ex) { Logger.getLogger(Dao.class.getName()).log(Level.SEVERE, null, ex); } try { stm.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); } } return list; } }

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 list = Dao.getAllUser(); root.removeAllChildren(); for (int i = 0; i < list.size(); i++) { User1 user = list.get(i); //System.out.println(user.getUsername()); root.add(new DefaultMutableTreeNode(user)); } treeModel.reload(); UserTree.this.setSelectionRow(0); } catch (InterruptedException ex) { Logger.getLogger(UserTree.class.getName()).log(Level.SEVERE, null, ex); } } } ).start(); } public void addUser(User1 user) { Dao.addUser(user); root.add(new DefaultMutableTreeNode(user)); treeModel.reload(); } public void delUser() { TreePath path=getSelectionPath(); User1 user=(User1)((DefaultMutableTreeNode)path.getLastPathComponent()).getUserObject(); root.remove(new DefaultMutableTreeNode(user)); treeModel.reload(); Dao.delUser(user); } }

界面:

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") // private void initComponents() { jLabel1 = new javax.swing.JLabel(); jTextField1 = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); jTextField2 = new javax.swing.JTextField(); jPanel1 = new javax.swing.JPanel(); jButton1 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel1.setText("用户名:"); jLabel1.setName("jLabel1"); // NOI18N jTextField1.setName("jTextField1"); // NOI18N jLabel2.setText("图片路径:"); jLabel2.setName("jLabel2"); // NOI18N jTextField2.setName("jTextField2"); // NOI18N jPanel1.setName("jPanel1"); // NOI18N javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 380, Short.MAX_VALUE) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 316, Short.MAX_VALUE) ); jButton1.setText("添加"); jButton1.setName("jButton1"); // NOI18N jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(50, 50, 50) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel2) .addGap(18, 18, 18) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel1) .addGap(29, 29, 29) .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 175, Short.MAX_VALUE))) .addGap(31, 31, 31) .addComponent(jButton1) .addGap(52, 52, 52)))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(33, 33, 33) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton1)) .addGap(32, 32, 32) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(31, Short.MAX_VALUE)) ); pack(); }// private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: User1 user=new User1(); user.setUsername(jTextField1.getText().trim()); user.setImageurl(jTextField2.getText().trim()); mytree.addUser(user); } /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new MainFrame().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JPanel jPanel1; private javax.swing.JTextField jTextField1; private javax.swing.JTextField jTextField2; // End of variables declaration }

你可能感兴趣的:(JAVA)