1

我有一个名为 tree1 的数据库表,它有一个名为 student_details 的表。这个表有 3 列 student_name、student_details、student_phone

现在,我能够从数据库中检索学生详细信息,但只能以静态方式。

问题是当我插入一个新的学生详细信息行 {student_name,student_details,student_phone} 我希望它显示在我的 Jtree 上。虽然 Hashmap 是解决方案,但我无法理解如何在 Jtree 中使用 hashmap 来创建动态节点。

下面是我可以做一个静态Jtree的代码,我想让它动态化。谁能告诉我如何使用代码示例来做到这一点?

package tree_try;


import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.beans.Statement;
import java.sql.*;
import java.util.ArrayList;
import java.util.Iterator;
import javax.swing.*;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.*;


public class SimpleTree extends JFrame
{
   public Connection connect = null;


   public Statement statement = null;
   public Statement statement2 = null;
    public Statement statement3 = null;
      public Statement statement4 = null;
   public Statement statement5 = null;
    public Statement statement6 = null;

   public ResultSet resultSet = null;
   public ResultSet resultSet2 = null;
    public ResultSet resultSet3 = null;
     public ResultSet resultSet4 = null;
   public ResultSet resultSet5 = null;
    public ResultSet resultSet6 = null;



   public ArrayList arrayList = new ArrayList();
   public ArrayList arrayList2 = new ArrayList();
   public ArrayList arrayList3 = new ArrayList();
   public ArrayList arrayList4 = new ArrayList();

   static String store[] = new String[10];
   static String store2[] = new String[10];
   static String store3[] = new String[10];

   //for the panel

   static String store4[] = new String[10];
   static String store5[] = new String[10];
   static String store6[] = new String[10];
    static String store7[] = new String[10];

   //for panel over


   int i=0;
   int i1=0;
   int i2=0;
   int i3=0;



    JPanel jp1 = new JPanel();
    JPanel jp2 = new JPanel();
    JFrame jf1 = new JFrame();

    JButton jb1 = new JButton("Save");
       JButton jb2 = new JButton("Cancel");

    JTextField jt1= new JTextField();
    JTextField jt2 = new JTextField();
    JTextField jt3= new JTextField();
    JTextField jt4 = new JTextField();



    JLabel jl0 = new JLabel();

    JLabel jl1 = new JLabel("Name : ");
    JLabel jl2 = new JLabel("Adress : ");
    JLabel jl3 = new JLabel("Phone Number : ");
    JLabel jl4 = new JLabel("Other Deatils : ");
    JLabel jl5 = new JLabel("");


  public static void main(String[] args)
  {
    new SimpleTree();
  }

  public SimpleTree() 
  {

    super("Schools database");
    WindowUtilities.setNativeLookAndFeel();
    addWindowListener(new ExitListener());





     //db part
      try 
                {
            Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
            connect = DriverManager.getConnection("jdbc:derby://localhost:1527/treedata1","suraj","suraj");
            PreparedStatement statement = connect.prepareStatement("SELECT * from school_details");
                        PreparedStatement statement2 = connect.prepareStatement("select student_name from student_details where s_id =1");   
                         PreparedStatement statement3 = connect.prepareStatement("select student_name from student_details where s_id =2");   

                         //for the panel display


                         //PreparedStatement statement5 = connect.prepareStatement("select student_name from student_details where s_id =1");   
                         //PreparedStatement statement6 = connect.prepareStatement("select student_name from student_details where s_id =2");



            resultSet = statement.executeQuery();
            while (resultSet.next()) 
                        {
                String sname = resultSet.getString("school_name");
                String sid = resultSet.getString("s_id");
                arrayList.add(sname);
                                System.out.println("this is stsement one"+sname);
                                //arrayList.add(number);

            }

                        resultSet2 = statement2.executeQuery(); 
                        while (resultSet2.next())
                        {
                                String user2 = resultSet2.getString("student_name");
                //int  number2 = resultSet2.getInt("s_id");
                                arrayList2.add(user2);
                                System.out.println("this is stsement two"+user2);
                        }
                      //  System.out.println(arrayList); 
                         resultSet3 = statement3.executeQuery(); 
                        while (resultSet3.next())
                        {
                                String user3 = resultSet3.getString("student_name");
                //int  number2 = resultSet2.getInt("s_id");
                                arrayList3.add(user3);
                                System.out.println("this is stsement three"+user3);
                        }
                        System.out.println("this is after statement 3 before 4");



        } 
                catch (Exception e2) 
                {
            e2.printStackTrace();
        } 





      //
    Iterator it = arrayList.iterator();
    while (it.hasNext()) 
    {
         store[i]= (String) it.next();
         i++; 
                 //System.out.println(it.next());
    }


    Iterator it2 = arrayList2.iterator();
    while (it2.hasNext()) 
    {
         store2[i1]= (String) it2.next();
         i1++;        
        //System.out.println(it.next());
    }

     Iterator it3 = arrayList3.iterator();
    while (it3.hasNext()) 
    {
         store3[i2]= (String) it3.next();
         i2++;        
       // System.out.println(it.next());
    }








    // ------------------------- Visible Settings start here --------------------//

     Object[] hierarchy ={"Click for schools",new Object[] {store[0],new Object[] { "Student Details",store2[0],store2[1] } },new Object[] { store[1],new Object[] { "Student Details",store3[0],store3[1]}}};
    DefaultMutableTreeNode root = processHierarchy(hierarchy);
    final JTree tree = new JTree(root);

   // setSize(275, 300);
    jp1.setSize(50,50);
    jp1.setBackground(Color.WHITE);
    jf1.setExtendedState(Frame.MAXIMIZED_BOTH);
    jf1.setLayout(new GridLayout(1,2));
    jf1.setVisible(true);
    jf1.add(new JScrollPane(tree), BorderLayout.WEST);
    jf1.add(jp1);
    jp1.setLayout(null);

  jl0.setBounds(10,1,500,100);  
  jp1.add(jl0);


 jl1.setBounds(55,90,150,100);   
 jt1.setBounds(225,130, 155, 25);

 jp1.add(jl1);
 jp1.add(jt1);

 jl2.setBounds(55,160, 150, 100);
 jt2.setBounds(225,200, 155, 25);

 jp1.add(jl2);
 jp1.add(jt2);

 jl3.setBounds(55,230,150,100);
 jt3.setBounds(225,270, 155, 25);

  jp1.add(jl3);
  jp1.add(jt3);

 jl4.setBounds(55,295, 150, 100);
 jt4.setBounds(225,330, 155, 25);

  jp1.add(jl4); 
  jp1.add(jt4);

  jb1.setEnabled(false);
  jb2.setEnabled(false);

 jb1.setBounds(150,430, 100, 50);
 jb2.setBounds(350,430, 100, 50);

  jp1.add(jb1);
  jp1.add(jb2);

  //-----------------Visible setting stop here--------------------------//

   //------------------- Element actions here------------------------//


    jt1.addFocusListener(new FocusListener() {

            @Override
            public void focusGained(FocusEvent e) 
            {
             jb1.setEnabled(true);
             jb2.setEnabled(true);    
            }

            @Override
            public void focusLost(FocusEvent e) 
            {
                jb1.setEnabled(false);
                jb2.setEnabled(false); 
            }
        });

    //now for the tree

    tree.addTreeSelectionListener(new TreeSelectionListener() {

            @Override
            public void valueChanged(TreeSelectionEvent e) {
                jf1.dispose();
                //jl0.setText("Displaying information About :  "+tree.getLastSelectedPathComponent().toString());
                store7[0]= tree.getLastSelectedPathComponent().toString(); 
                System.out.println("in store 7 of 0"+store7[0]);
                dbaction db = new dbaction(store7[0]);
            }
        }); 

   }
//------------------------------------end of action listening-------------------------

  private DefaultMutableTreeNode processHierarchy(Object[] hierarchy) 
  {
    DefaultMutableTreeNode node = new DefaultMutableTreeNode(hierarchy[0]);DefaultMutableTreeNode child;
    for(int i=1; i<hierarchy.length; i++) 
    {
      Object nodeSpecifier = hierarchy[i];
      if (nodeSpecifier instanceof Object[])  // Ie node with children
        child = processHierarchy((Object[])nodeSpecifier);
      else
        child = new DefaultMutableTreeNode(nodeSpecifier); // Ie Leaf
      node.add(child);
    }
    return(node);
  }

    private void close() 
    {
        try {
            if (resultSet != null) 
                        {
                resultSet.close();
            }
            if (statement != null) 
                        {
                //statement.
            }
            if (connect != null) 
                        {
                connect.close();
            }
        } 
        catch (Exception e3) 
                {
        e3.printStackTrace();
        }
    }
}

当然 dbaction.java 是我连接到数据库并获取详细信息的地方。

4

2 回答 2

2

最好为树创建数据模型。如何使用树教程有很好的例子。还可以通过了解 TreeModel了解更多详细信息。

顺便说一句,不要执行长时间运行的任务,例如在Event Dispatch Thread上访问数据库。查看SwingWorker以完成此类任务。

于 2012-07-17T05:02:34.683 回答
2

Max 链接到的JTree教程有一节涵盖“a 的动态更新JTree,其中包含有关如何更新 a 的必要片段TreeModel。基本思想是更新JTree( TreeModel) 后面的模型并从TreeModel. 将JTree监听这些事件并相应地更新自身。

除此之外,还有其他一些建议:

  • You should only access Swing components on the Event Dispatch Thread (EDT), which is currently not the case in your example. See the Concurrency in Swing tutorial for more information
  • The moment you adjust your main method to run on the EDT, you should avoid the long running taks (the database access), as it will block the EDT and leave you with an unresponsive UI (as Max already indicated).
  • You should avoid the null layout and the manual placing of all your components using setBounds. Otherwise simple things like resizing the UI will results in a messed-up layout. Use a LayoutManager instead. The usage of LayoutManagers is also covered in the 'LayoutManager tutorial' on the Oracle site.
于 2012-07-17T06:08:14.720 回答