Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在JTree上显示动态更新?/如何刷新或重新加载JTree?_Java_Swing_Jtree - Fatal编程技术网

Java 如何在JTree上显示动态更新?/如何刷新或重新加载JTree?

Java 如何在JTree上显示动态更新?/如何刷新或重新加载JTree?,java,swing,jtree,Java,Swing,Jtree,应用程序很简单,一个框架中有两个面板 第一个面板,从数据库中检索所有学生,使用多个hashmap获取父和子排列,并在树上显示它 第二个面板,当您单击某个学生时,该学生的所有详细信息(selectionlistener)显示在文本框中 现在,当我在第二个面板上更改学生的名字时,数据库会正确地更新它,但树会显示旧的值 我尝试了treepanel.reload(),我尝试了treemodellistener 有人能帮我吗。在网上浏览了很多解决方案后,所有的解决方案都是局部的,我无法将它们应用到我的代码

应用程序很简单,一个框架中有两个面板

  • 第一个面板,从数据库中检索所有学生,使用多个hashmap获取父和子排列,并在树上显示它

  • 第二个面板,当您单击某个学生时,该学生的所有详细信息(selectionlistener)显示在文本框中

  • 现在,当我在第二个面板上更改学生的名字时,数据库会正确地更新它,但树会显示旧的值

    我尝试了treepanel.reload(),我尝试了treemodellistener

    有人能帮我吗。在网上浏览了很多解决方案后,所有的解决方案都是局部的,我无法将它们应用到我的代码中

    提前谢谢


    Main frame.java

    /**
     * @author Suraj Baliga
     * 
     * Returns a JFrame with two Panels one having the Jtree and other 
     * having the details of the selected tree component.It also has dynamic tree and 
     * dynamic textbox where updation of text in the textbox will change the value in 
     * databse on click of save button.The JDBC localhost url may change with each machine 
     * as the database location and port number may vary.
    */
    
    
    
    
    package Student_Details;
    
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.FocusEvent;
    import java.awt.event.FocusListener;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.Iterator;
    import java.util.Set;
    import javax.swing.*;
    import javax.swing.tree.DefaultMutableTreeNode;
    import org.apache.commons.collections.MultiHashMap;
    
    public final class Main_frame extends JPanel 
    {
        String sname,sschool;
    
        ArrayList StudName_arrylst = new ArrayList();
        ArrayList SchlName_arrylst = new ArrayList();
        ArrayList StudDetailTxtFld_arrylst = new ArrayList();
    
    
        static public Connection connect,connect_update;
        public ResultSet resultSet;
        public static ResultSet resultset2;
        MultiHashMap SchlStud_hashmap = new MultiHashMap();
    
        int i,j,k,k2,z;
    
        DefaultMutableTreeNode tree_parent;
        int SchlName_arylist_length, StudNamearrylst_length;
        private tree_generation treePanel;
    
    
        static JButton save_button = new JButton("Save");
        static JButton cancel_button = new JButton("Cancel");
    
        static JTextField studName_txtbox= new JTextField();
        static JTextField studAddress_txtbox = new JTextField();
        static JTextField studOthr_txtbox = new JTextField();
    
       static public String user_name;
       static public String user_add;
       static public String user_other;
    
    
    
    
        static JLabel name_label = new JLabel("Name : ");
        static JLabel address_label = new JLabel("Adress : ");
        static JLabel other_label = new JLabel("Other Deatils : ");
    
       static String studDetailsTxtbox_disp[] = new String[10];
        static String studDetailsTxtbx_disp_db[] = new String[10];
        static String studDetailsTxtbxchange[] = new String[10];
    
        public JPanel panel;
        static JPanel panel_boxes = new JPanel();
    
    
    
    
        public Main_frame() 
        {
    
            super(new BorderLayout());
    
            //Create the components.
            treePanel = new tree_generation();
            populateTree(treePanel);
    
            //Lay everything out.
            treePanel.setPreferredSize(new Dimension(300, 150));
            add(treePanel, BorderLayout.WEST);
    
            panel = new JPanel(new GridLayout(1, 2));
            add(panel, BorderLayout.CENTER); 
         }
    
    
    
    
    
    
        public void populateTree(tree_generation treePanel) 
        {
            try 
            {
                Class.forName("org.apache.derby.jdbc.ClientDriver");
                connect = DriverManager.getConnection("jdbc:derby://localhost:1527/treedata2", "suraj", "suraj");
                PreparedStatement AllStuddetails = connect.prepareStatement("SELECT * from student_details");
                resultSet = AllStuddetails.executeQuery();
                while (resultSet.next()) 
                {
    
                    sname = resultSet.getString(1);
                    sschool = resultSet.getString(3);
                    SchlStud_hashmap.put(sschool, sname);
                }
            } 
            catch (Exception e) 
             {
    
             }
            Set keySet = SchlStud_hashmap.keySet();
            Iterator keyIterator = keySet.iterator();
    
            while (keyIterator.hasNext())
            {
                Object key = keyIterator.next();
                SchlName_arrylst.add(key);
    
                Collection values = (Collection) SchlStud_hashmap.get(key);
                Iterator valuesIterator = values.iterator();
    
                while (valuesIterator.hasNext()) 
                {
                    StudName_arrylst.add(valuesIterator.next());
    
                }
                SchlName_arylist_length = SchlName_arrylst.size();
                StudNamearrylst_length = StudName_arrylst.size();
    
                String schlname_tree[] = new String[SchlName_arylist_length];
                String studname_tree[] = new String[StudNamearrylst_length];
    
                Iterator SchlName_iterator = SchlName_arrylst.iterator();
    
                i = 0;
                while (SchlName_iterator.hasNext()) 
                {
                    schlname_tree[i] = SchlName_iterator.next().toString();
                }
    
                Iterator StudName_iterator = StudName_arrylst.iterator();
                j = 0;
                while (StudName_iterator.hasNext()) 
                {
                    studname_tree[j] = StudName_iterator.next().toString();
                     j++;
                }
    
                for (k = 0; k < schlname_tree.length; k++) 
                {
                      tree_parent = treePanel.addObject(null, schlname_tree[k]);
                      for (k2 = 0; k2 < studname_tree.length; k2++) 
                         {
                                treePanel.addObject(tree_parent, studname_tree[k2]);
                         }
                }
               StudName_arrylst.clear();
               SchlName_arrylst.clear();
             }
    
      }
    
    
    
    
    
    
    
        /**
         * Create the GUI and show it.  
         */
        private static void createAndShowGUI() 
        {
            //Create and set up the window.
            JFrame frame = new JFrame("Student Details");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
            //Create and set up the content pane.
            Main_frame newContentPane = new Main_frame();
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.setContentPane(newContentPane);
            panel_boxes.setLayout(null);
    
            name_label.setBounds(55,90,150,100);   
            studName_txtbox.setBounds(225,130, 155, 25);
            panel_boxes.add(name_label);
            panel_boxes.add(studName_txtbox);
    
    
            address_label.setBounds(55,160, 150, 100);
            studAddress_txtbox.setBounds(225,200, 155, 25);
            panel_boxes.add(address_label);
            panel_boxes.add(studAddress_txtbox);
    
            other_label.setBounds(55,220, 150, 100);
            studOthr_txtbox.setBounds(225,270, 155, 25);
            panel_boxes.add(other_label); 
            panel_boxes.add(studOthr_txtbox);
    
    
            save_button.setBounds(150,350, 100, 50);
            cancel_button.setBounds(350,350, 100, 50);
            panel_boxes.add(save_button);
            panel_boxes.add(cancel_button); 
    
            frame.add(panel_boxes); 
            //Display the window.
            frame.pack();
            frame.setSize(1000,700);
            frame.setVisible(true);
    
    
            save_button.setEnabled(false);
            cancel_button.setEnabled(false);
    
    
             studName_txtbox.addFocusListener(new FocusListener() 
             {
                @Override //since some additional functionality is added by the user to 
                          //the inbuilt function @override notation is used
                public void focusGained(FocusEvent e) 
                {
                 save_button.setEnabled(true);
                 cancel_button.setEnabled(true);
                }
    
                @Override
                public void focusLost(FocusEvent e) 
                {
                    System.out.println("out of focus textbox");
                }
    
    
            });
    
              studAddress_txtbox.addFocusListener(new FocusListener() {
    
                @Override
                public void focusGained(FocusEvent e) 
                {
                 save_button.setEnabled(true);
                 cancel_button.setEnabled(true);    
                }
    
                @Override
                public void focusLost(FocusEvent e) 
                {
                   save_button.setEnabled(false);
                    cancel_button.setEnabled(false); 
                }
            });
    
    
                studOthr_txtbox.addFocusListener(new FocusListener() {
    
                @Override
                public void focusGained(FocusEvent e) 
                {
                 save_button.setEnabled(true);
                 cancel_button.setEnabled(true);    
                }
    
                @Override
                public void focusLost(FocusEvent e) 
                {
                   save_button.setEnabled(false);
                    cancel_button.setEnabled(false); 
                }
            });
    
                 cancel_button.addActionListener(new ActionListener() 
            { 
                    public void actionPerformed(ActionEvent e) 
                    { 
                        if(e.getSource()== cancel_button )
                        {
                     clear_textboxes();
                     }
                    }
                  } );
                save_button.addActionListener(new ActionListener() 
            { 
                    public void actionPerformed(ActionEvent e) 
                    { 
                        if(e.getSource()== save_button )
                        {
                     selectionButtonPressed();
                     }
                    }
                  } );
        }
    
    
    
    
         public void fill_textboxes(ArrayList a1)
        {
            Iterator alldetails = a1.iterator();
            z=0;
            while (alldetails.hasNext()) 
             {
              studDetailsTxtbx_disp_db[z]= (String) alldetails.next();
              System.out.println("this is the Detail : "+studDetailsTxtbx_disp_db[z]);
               z++;   
             }  
    
         studName_txtbox.setText(studDetailsTxtbx_disp_db[0]);
         studAddress_txtbox.setText(studDetailsTxtbx_disp_db[1].toString());
         studOthr_txtbox.setText(studDetailsTxtbx_disp_db[2]);
    
     }
      public static void selectionButtonPressed()
        {
          studDetailsTxtbxchange[0]=studName_txtbox.getText(); 
          studDetailsTxtbxchange[1]=studAddress_txtbox.getText();
          studDetailsTxtbxchange[2]=studOthr_txtbox.getText();
          try 
            {
                if((studDetailsTxtbxchange[0].equals(""))||(studDetailsTxtbxchange[0] == null)||(studDetailsTxtbxchange[1].equals(""))||(studDetailsTxtbxchange[1] == null)||(studDetailsTxtbxchange[2].equals(""))||(studDetailsTxtbxchange[2] == null))
                {
                JOptionPane.showMessageDialog(null,"One of the Fields is Blank","Error",JOptionPane.ERROR_MESSAGE);
                }
                else
                {
                System.out.println("control here inside else baby..that has : : "+studDetailsTxtbxchange[0]);
                Class.forName("org.apache.derby.jdbc.ClientDriver");
                connect_update = DriverManager.getConnection("jdbc:derby://localhost:1527/treedata2", "suraj", "suraj");
                PreparedStatement execqry = connect.prepareStatement("select * from student_details where student_name='"+studDetailsTxtbxchange[0]+"'");
                resultset2=execqry.executeQuery();
                 System.out.println("control at end if else");
                if(resultset2.next())
                {
                    JOptionPane.showMessageDialog(null,"Sorry This name already exists","Error",JOptionPane.ERROR_MESSAGE);
                }
                else
                {
                   System.out.println("control here");
                   Class.forName("org.apache.derby.jdbc.ClientDriver");
                   connect_update = DriverManager.getConnection("jdbc:derby://localhost:1527/treedata2", "suraj", "suraj");
                   PreparedStatement updateQry = connect.prepareStatement("UPDATE student_details SET student_name='"+studDetailsTxtbxchange[0]+"',student_address='"+studDetailsTxtbxchange[1]+"',student_school='"+studDetailsTxtbxchange[2]+"' WHERE student_name='"+user_name+"' and student_address='"+user_add+"'and student_school='"+user_other+"'");
                   updateQry.executeUpdate();
                   JOptionPane.showMessageDialog(null,"Record Updated!","UPDATED",JOptionPane.OK_OPTION);
                      tree_generation.loadit();
                }
    
                } 
    
            }
            catch (Exception e) 
             {
               e.printStackTrace(); 
             }              
        }
    
      public static void clear_textboxes() 
         {
         studName_txtbox.setText(studDetailsTxtbx_disp_db[0]);
         studAddress_txtbox.setText(studDetailsTxtbx_disp_db[1].toString());
         studOthr_txtbox.setText(studDetailsTxtbx_disp_db[2]);
         }
    
        void dbaction(String string)
          {
    
          studDetailsTxtbox_disp[0]= string;
          System.out.println("This is the stuff :" + studDetailsTxtbox_disp[0]);
           try
           {
           Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
           connect = DriverManager.getConnection("jdbc:derby://localhost:1527/treedata2","suraj","suraj");
           PreparedStatement statement4 = connect.prepareStatement("SELECT * from student_details where student_name ='"+studDetailsTxtbox_disp[0]+"'");                
           resultSet = statement4.executeQuery();
           while(resultSet.next())
                       {
    
                                 user_name = resultSet.getString("student_name");
                                StudDetailTxtFld_arrylst.add(user_name);
                                System.out.println("name :"+user_name);
    
                                user_add = resultSet.getString("student_address");
                                StudDetailTxtFld_arrylst.add(user_add);
                                System.out.println("address : "+ user_add);
    
    
                                user_other = resultSet.getString("student_school");
                                StudDetailTxtFld_arrylst.add(user_other);
                                System.out.println("school : "+user_other);
                     }
    
        }
        catch (Exception e1) 
        {
            e1.printStackTrace();
        }
       fill_textboxes(StudDetailTxtFld_arrylst);
     }
    
    
    
    
        public static void main(String[] args) 
        {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
    
                public void run() 
                {
                    createAndShowGUI();
                }
            });
        }
    }
    
    查询-数据库名称:treedata2

    create table student_details(student_name varchar(20),student_address varchar(30),student_school varchar(20));
    
    insert into student_details values('suraj','mangalore','dps');
    insert into student_details values('prassana','Bangalore lalbagh 23/16 2nd main road','dps');
    insert into student_details values('deepika','Mangalore kadri park , 177b','dav');
    insert into student_details values('sujith','delhi , rajinder nagar, d black','dav');
    insert into student_details values('sanjay','bombay marina drive, 12/34','dav');
    insert into student_details values('suresh','jaipur , lalbagh cjhowki','kv');
    insert into student_details values('manu','surat, pune warior house','kv');
    insert into student_details values('tarun','chennai, glof club','salwan');
    insert into student_details values('vinay','haryana, indutrial area','hindu senior');
    insert into student_details values('veeru','trivendrum, kottayam 12/77','canara')
    

    好的,我想我在你的代码中发现了什么不起作用,但是你可能应该自己试试并确认一下

    Class.forName("org.apache.derby.jdbc.ClientDriver");
    connect_update = DriverManager.getConnection("jdbc:derby://localhost:1527/treedata2", "suraj", "suraj");
    PreparedStatement updateQry = connect.prepareStatement("UPDATE student_details SET student_name='"+studDetailsTxtbxchange[0]+"',student_address='"+studDetailsTxtbxchange[1]+"',student_school='"+studDetailsTxtbxchange[2]+"' WHERE student_name='"+user_name+"' and student_address='"+user_add+"'and student_school='"+user_other+"'");
    updateQry.executeUpdate();
    JOptionPane.showMessageDialog(null,"Record Updated!","UPDATED",JOptionPane.OK_OPTION);
    tree_generation.loadit();
    
    在这段代码中,您确实更新了数据库,但没有更新树的模型。您正在调用静态方法
    loadit()
    ,但该方法不包含任何代码。为了使用worker,您可能应该刷新/重新加载树模型。有不同的方法可以做到这一点。一种方法是直接定位树节点以刷新树节点,并用新值更新树节点。另一种方法是重新创建整个TreeModel(但如果树很大,这可能会很昂贵)。使用对象映射模型(例如JPA/Hibernate),您可以通过适当的MVC模式和通知视图更新值的模型来获得更清晰的内容,但这需要额外的设置工作

    <>因为它是有价值的,你应该考虑放弃那些<代码>静态< /代码>关键字,因为它们不是必需的,也不是适当使用的。尽可能避免使用该关键字(除非它与
    final
    一起用于描述常量值)


    还有一件事,尝试使用适当的,而不是使用绝对定位。使用适当的布局管理器可以使您的代码更易于维护,并且在不同的平台/外观上更易于移植。

    考虑简化您的代码,使其对我们来说是可运行的,但删除了所有数据库引用,删除了所有与问题无关的代码,以便隔离问题,如果问题仍然存在,允许我们在不需要数据库的情况下运行您的代码,在不检查大量无关代码的情况下检查您的代码,并希望允许我们找到解决方案。嗨,气垫船上满是鳗鱼,感谢您的检查。实际上,代码是可运行的。数据库文件也在那里,您只需将其复制粘贴到netbeans derby中即可。将java文件粘贴到新的项目文件夹中并运行。让我知道我是否应该移除它。@SurajB当然,移除不必要的东西。如果不创建数据库、添加公共集合等,代码将无法运行。。。这使得其他人很不愿意获取您的代码并执行它。代码太多,无法读取。Als,你应该考虑以下内容:1)不要默默地抓住一个例外(这是新手错误)2)正确缩进代码3)遵循java编码约定:类名以大写字母开头,包应该只包含小写字母,变量以小写字母开头…使用camel case而不是underscores@SurajB如果不修改外观或其任何属性,则不需要调用
    tree.updateUI()@Suraj:没有人要求你做出纪尧姆和我建议的改变,但通常你越容易让别人帮助你,你就越有机会得到快速的帮助。如果你得到了一个体面的解决方案而不做这些改变,那么很好,但如果没有,你仍然滞留,请考虑我们的建议。非常感谢你的输入Guillaume Polet。在可能的情况下,我会尝试删除静态文件,并设置一个布局管理器。至于刷新,你能指导我如何用我的代码刷新整个树吗?我知道这很昂贵,但这正是现在的需要。嗨,垃圾上帝,谢谢你关注我的问题。实际上,我访问了您提供的示例,但没有找到在哪里使用了重载。如果您能给我一个如何在JTree上实现它的指针,我将不胜感激。@SurajB:为我粗心的链接道歉;这个相关的使用了
    reload()
    。嗨,垃圾神,我确实访问了你的链接。在分析并尝试应用相同的原理之后,我注意到treeModel.reload()正在进行刷新工作。我尝试了同样的方法{我已经编辑了代码,请参阅loadit()函数},但没有成功。Jtree不会刷新。有什么建议吗?Guillaume Polet我确实在loadit()函数{i have edited it}中添加了treeModel.reload(),但它仍然不会用数据库中更改的值刷新
    Class.forName("org.apache.derby.jdbc.ClientDriver");
    connect_update = DriverManager.getConnection("jdbc:derby://localhost:1527/treedata2", "suraj", "suraj");
    PreparedStatement updateQry = connect.prepareStatement("UPDATE student_details SET student_name='"+studDetailsTxtbxchange[0]+"',student_address='"+studDetailsTxtbxchange[1]+"',student_school='"+studDetailsTxtbxchange[2]+"' WHERE student_name='"+user_name+"' and student_address='"+user_add+"'and student_school='"+user_other+"'");
    updateQry.executeUpdate();
    JOptionPane.showMessageDialog(null,"Record Updated!","UPDATED",JOptionPane.OK_OPTION);
    tree_generation.loadit();