JTree没有刷新和控制它加载新的JSON

时间:2017-05-01 15:35:37

标签: java json swing jtree

我在Java中解析JSON文件。清洁JSON,不是杰克逊,也不是GSON。 我的问题是当我加载一个新的.json文件时,我的JTree没有刷新。 我在stackoverflow和其他一些论坛上尝试了很多不同的选项,但我没有找到解决方案。

我将在下面编写我的程序代码。

NodeStorage,NodeEntity等是继承DefaultMutableTreeNode的NodeInfo的子类。

ViewTree扩展了DefaultTreeModel。

你应该专门查找的代码函数是 initialiseTree 所以我会在这里编写它和其余的代码(整个gui类将在另一个窗口中写在这个类下面):

public void initialiseTree() throws IOException, JSONException {
        this.setScrollPane(null);
        this.setJtree(null);
        this.setViewTree(null);
        if(this.getPathMetaschema() == null) {
            this.setNodeStorage(new NodeStorage(new ModelStorage("Empty root", "emptroot", null)));
        }
        else {
            JSONinit(pathMetaschema);
            setNodeStorage(new NodeStorage(this.getModelStorage()));
        }   
        this.setViewTree(new ViewTree(this.getNodeStorage()));
        this.getViewTree().setMyRoot(this.getNodeStorage());
        this.getViewTree().reload(this.getNodeStorage());
        this.getViewTree().nodeChanged(this.getViewTree().getMyRoot());
//      this.getViewTree().addTreeSelectionListener(new ControllerTree(this));
//      TODO: OVO NIJE BILO OVDE VEC JE BILO U INICIJALIZACIJI POCETNOJ. RESITI PROBLEM.
        setJtree(new JTree(this.getViewTree()));
        jtree.setEditable(true);
        DefaultMutableTreeNode currentNode = (DefaultMutableTreeNode) this.getViewTree().getRoot();
        do {
           if (currentNode.getLevel()==1) 
                jtree.expandPath(new TreePath(currentNode.getPath()));
           currentNode = currentNode.getNextNode();
           }
        while (currentNode != null);
//      jtree.setExpandsSelectedPaths(false);
        jtree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
        scrollPane = new JScrollPane(this.getJtree());
        add(scrollPane, BorderLayout.WEST);
        getJtree().setCellRenderer(new MyTreeCellRenderer());
        SwingUtilities.updateComponentTreeUI(this.getJtree());

//      scrollPane.repaint();
//      this.getJtree().repaint();
//      this.repaint();
//      this.revalidate();
//      this.validate();
    }

以下是该课程的代码:

    /** 
     * Main view class that will provide all the gui needed.
     * It extends <code>JFrame</code>.
     * 
     * @author Ivan, Strahinja, Vukasin
     */
    public class View extends JFrame {

        private static final long serialVersionUID = 1L;

        /**
         * Model of storage that will get storage from the database via JSON.
         */
        private ModelStorage modelStorage;
        /**
          * Model of entity that will be previewed. It's received from <code>JSON</code> and from modelStorage.
          */
        private ModelEntity modelEntity;

        /**
         * Instace of class <code>ViewOurMenuBar</code>
         */
        private ViewOurMenuBar ourMenuBar;

        /**
         * Instace of class <code>ViewToolBar</code>
         */
        private ViewToolBar toolBar;

        /**
         * Instace of class <code>ViewTree</code>
         */
        private ViewTree viewTree;

        /**
         * Instance of class <code>ViewTable</code> that will provide upper table on the view.
         * In it data is showed and attributes(colons) are loaded
         */
        private ViewTable gornjaTable;

        /**
         * Instace of class <code>ViewTable</code> that will provide bottom table on the view.
         * In it data is showed and attributes(colons) are loaded
         */
        private ViewTable donjaTable;
        private ViewToolBar tableUpToolBar;

        private NodeStorage nodeStorage;
        private NodeEntity ne;

        private JTable tblStudenti;
        private JTable tblStudenti02;


        private JSplitPane splitTables;
        private JSplitPane split;
        private JScrollPane scrollPane;
        private JTabbedPane tabbedPane;

        private JScrollPane scrollTb1;
        private JScrollPane scrollTb2;

        private JPanel panelUp;
        private JPanel panelDown;

        private String pathMetaschema;

        private JTree jtree;

        public View() throws IOException, JSONException {
            this.setPathMetaschema(null);
            this.initialise();
        }

        public View(String path) throws IOException, JSONException {
            this.setPathMetaschema(path);
    //      this.JSONinit(path);
            this.initialise();

        }

        public void initialise() throws IOException, JSONException {

            this.setTitle("InfoViewer");

            /*
             * Initialisation of the JFrame position, size and location.
             */
            Toolkit kit = Toolkit.getDefaultToolkit();
            Dimension screenSize = kit.getScreenSize();
            int screenWidth = screenSize.width;
            int screenHeight = screenSize.height;

            this.setSize(2*screenWidth/3, 2*screenHeight/3);
            this.setLocationRelativeTo(null);
            this.setDefaultCloseOperation(EXIT_ON_CLOSE);

            /*
             * Icon of the InfoViewer.
             */
            Image image = kit.getImage("images/IconInfoViewer.png");
            setIconImage(image);


            /*
             * Other initialization methods:
             * LookAndFeel, MenuBar, ToolBar, Tree.
             */
            this.initialiseLookAndFeel();       
            this.initialiseMenuBar();
            this.initialiseToolBar();
            this.initialiseTree();
            tabbedPane = new JTabbedPane();
            scrollTb1 = new JScrollPane();
            setScrollTb2(new JScrollPane());
            splitTables = new JSplitPane();
            split = new JSplitPane();
            panelUp = new JPanel(new BorderLayout());
            panelDown = new JPanel(new BorderLayout());
            tableUpToolBar = new ViewToolBar();
    //      scrollPane = new JScrollPane(this.getJtree());

    //      Object[] columns = new Object[] { "Dosije", "Ime", "Prezime" }; 
    //      Object[][] data = { 
    //              { "ra1/2011", "Petar", "Petrovic" },
    //              { "ra1/2011", "Lazar", "Lazić" },
    //              { "ra2/2011", "Milan", "Kova�ević" },
    //              { "ra3/2011", "Ana", "Petrović" },
    //              { "ra4/2011", "Bojan", "Bakić" },
    //              { "ra5/2011", "Dragan", "Kova�ević" },
    //              { "ra6/2011", "Ivan", "Ivić" } };

    //      this.getViewTree().addMouseListener(new ControllerTree(this.getViewTree()));
        //  this.getViewTree().setCellRenderer(new MyTreeCellRenderer());
        //  this.getOurMenuBar().addMouseListener(new ControllerMenuBar(this.getOurMenuBar())); 
        }

        public JSplitPane getSplit() {
            return split;
        }

        private boolean isValidJSON (String jsonString){
             boolean valid = false;
               try {
                  @SuppressWarnings("deprecation")
                final JsonParser parser = new ObjectMapper().getJsonFactory()
                        .createJsonParser(jsonString);
                  while (parser.nextToken() != null) {
                  }
                  valid = true;
               } catch (JsonParseException jpe) {
                  //jpe.printStackTrace();
               } catch (IOException ioe) {
                 // ioe.printStackTrace();
               }

               return valid;
        }

        public String loadJson(String metaschemaPath) throws IOException{

            BufferedReader bf1 = new BufferedReader(new InputStreamReader(
                    new FileInputStream(new File(metaschemaPath))));

            StringBuilder sb = new StringBuilder();
            String line = bf1.readLine();

                    while (line != null) {
                        sb.append(line);
                        sb.append("\n");
                        line = bf1.readLine();
                    }
                    bf1.close();
              return sb.toString();
        }

        public void JSONinit(String path) throws IOException, JSONException {
            String metaschemaPath = path;
    //      System.out.println("JSON INIT ENTER");
            String json = loadJson(metaschemaPath);
    //      System.out.println(isValidJSON(json));
            if (isValidJSON(json)){
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    new FileInputStream(new File(metaschemaPath))));
            JSONTokener tokener = new JSONTokener(bf);
            JSONObject object = new JSONObject(tokener);
            bf.close();

            String storageName = object.getJSONObject("storage").getString("name");
            String storageKey = object.getJSONObject("storage").getString("key");
            this.modelStorage = new ModelStorage(storageName, storageKey, metaschemaPath);
            System.out.println("Storage: " + this.modelStorage.getName() + " ,Key: " + this.modelStorage.getKey());

            JSONArray arrayPackages = object.getJSONObject("storage").getJSONArray("packages");

            for(int i = 0; i < arrayPackages.length(); i++) {
    //          U�itavanje paketa
                JSONObject packageObject = arrayPackages.getJSONObject(i);
                String name = packageObject.getString("name");
                String key = packageObject.getString("key");
                System.out.println("********* " + name + " ***********");
                ModelPackage modelPackage = new ModelPackage(name, key);
    //          U�itavanje liste paketa u ovaj paket.
                JSONArray arrayListOfPackages = packageObject.getJSONArray("listOfPackages");

    //          *** ***
    //          Šta ćemo da radimo ako u listi paketa paket sadrži i entitete i druge pakete?
                for(int j = 0; j < arrayListOfPackages.length(); j++) {
                    JSONObject listOfPackagesObject = arrayListOfPackages.getJSONObject(j);
                    String namePackage = listOfPackagesObject.getString("name");
                    String keyPackage = listOfPackagesObject.getString("key");
                    ModelPackage modelListPackage = new ModelPackage(namePackage, keyPackage);
                    modelPackage.getPackages().add(modelListPackage);

                    System.out.println("\tPackage: " + modelListPackage.getName() + ", Key: " + modelListPackage.getKey());
                }
    //          U�itavanje entiteta u paket
                JSONArray arrayListOfEntities = packageObject.getJSONArray("entities");
                for(int k = 0; k < arrayListOfEntities.length(); k++) {
                    JSONObject entityObject = arrayListOfEntities.getJSONObject(k);
                    String nameEntity = entityObject.getString("name");
                    String keyEntity = entityObject.getString("key");
                    ModelEntity modelEntity = new ModelEntity(nameEntity, keyEntity);
                    System.out.println("\t\tEntity: " + modelEntity.getName() + ", Key: " + modelEntity.getKey());

    //              U�itavanje atributa entiteta
                    JSONArray arrayAttributes = entityObject.getJSONArray("attributes");
                    for(int m = 0; m < arrayAttributes.length(); m++) {
                        JSONObject attributeObject = arrayAttributes.getJSONObject(m);
                        String nameAttribute = attributeObject.getString("name");
                        String keyAttribute = attributeObject.getString("key");
                        ModelAttribute modelAttribute = new ModelAttribute(nameAttribute, keyAttribute);
                        System.out.println("\t\t\tAttribute: " + modelAttribute.getName() + ", Key: " + modelAttribute.getKey());

                        modelEntity.getAttributes().add(modelAttribute);
                    }

    //              U�itavanje relacija entiteta
                    JSONArray arrayRelations = entityObject.getJSONArray("relations");
                    for(int m = 0; m < arrayRelations.length(); m++) {
                        JSONObject relationObject = arrayRelations.getJSONObject(m);
                        String nameRelation = relationObject.getString("name");
                        String keyRelation = relationObject.getString("key");
                        String linkedEntityKey = relationObject.getString("linkedEntityKey");
                        ModelRelation modelRelation = new ModelRelation(nameRelation, keyRelation, modelEntity, linkedEntityKey);
                        System.out.println("\t\t\tRelation: " + modelRelation.getName() + ", Key: " + modelRelation.getKey());
                        modelEntity.getRelations().add(modelRelation);
                    }

                    modelPackage.getEntities().add(modelEntity);
                }

                this.modelStorage.getPackages().add(modelPackage);
            }
            } else {
                System.out.println("JSON metasema nije validna!");
                System.exit(0);
            }

            System.out.println("--------------------------------------------------------------");
            System.out.println(this.modelStorage.getName() + ": ");
            System.out.println("Packages:");
            for(ModelPackage mp: this.modelStorage.getPackages()) {
                System.out.println("\t" + mp.getName() + ": ");
                System.out.println("\t\tPackages:");
                for(ModelPackage mp2: mp.getPackages()) {
                    System.out.println("\t\t\t" + mp2.getName());
                }
                System.out.println("\t\tEntities:");
                for(ModelEntity me: mp.getEntities()) {
                    System.out.println("\t\t\t\t" + me.getName() + ": ");
                    System.out.println("\t\t\t\tAttributes:");
                    for(ModelAttribute ma: me.getAttributes()) {
                        System.out.println("\t\t\t\t\t" + ma.getName());
                    }
                    System.out.println("\t\t\t\tRelations:");
                    for(ModelRelation mr: me.getRelations()) {
                        System.out.println("\t\t\t\t\t" + mr.getName() + " " + mr.getLinkedEntityKey());
                    }
                }
            }

    //      System.out.println("JSON INIT EXIT");
        }

        public JScrollPane getScrollTb1()
        {
            return scrollTb1;
        }

        public void setScrollTb1(JScrollPane scrollTb1)
        {
            this.scrollTb1 = scrollTb1;
        }

        public void initialiseTree() throws IOException, JSONException {
            this.setScrollPane(null);
            this.setJtree(null);
            this.setViewTree(null);
            if(this.getPathMetaschema() == null) {
                this.setNodeStorage(new NodeStorage(new ModelStorage("Empty root", "emptroot", null)));
            }
            else {
                JSONinit(pathMetaschema);
                setNodeStorage(new NodeStorage(this.getModelStorage()));
            }   
            this.setViewTree(new ViewTree(this.getNodeStorage()));
            this.getViewTree().setMyRoot(this.getNodeStorage());
            this.getViewTree().reload(this.getNodeStorage());
            this.getViewTree().nodeChanged(this.getViewTree().getMyRoot());
    //      this.getViewTree().addTreeSelectionListener(new ControllerTree(this));
    //      TODO: OVO NIJE BILO OVDE VEC JE BILO U INICIJALIZACIJI POCETNOJ. RESITI PROBLEM.
            setJtree(new JTree(this.getViewTree()));
            jtree.setEditable(true);
            DefaultMutableTreeNode currentNode = (DefaultMutableTreeNode) this.getViewTree().getRoot();
            do {
               if (currentNode.getLevel()==1) 
                    jtree.expandPath(new TreePath(currentNode.getPath()));
               currentNode = currentNode.getNextNode();
               }
            while (currentNode != null);
    //      jtree.setExpandsSelectedPaths(false);
            jtree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
            scrollPane = new JScrollPane(this.getJtree());
            add(scrollPane, BorderLayout.WEST);
            getJtree().setCellRenderer(new MyTreeCellRenderer());
            SwingUtilities.updateComponentTreeUI(this.getJtree());

    //      scrollPane.repaint();
    //      this.getJtree().repaint();
    //      this.repaint();
    //      this.revalidate();
    //      this.validate();
        }

        public void initialiseToolBar() {

            setToolBar(new ViewToolBar());
            add(getToolBar(), BorderLayout.NORTH);

        }

        public void initialiseMenuBar() {
            this.setOurMenuBar(new ViewOurMenuBar(this.getPathMetaschema()));
            this.setJMenuBar(this.getOurMenuBar()); 
        }

        public void initialiseGornjaTable() {   
            //      System.out.println("Inicijalizacija tabele");
            this.setGornjaTable(new ViewTable(modelEntity));
    //      System.out.println(modelEntity.getName());
            tblStudenti = new JTable(this.gornjaTable.getData(), this.getGornjaTable().getColumns());
            tblStudenti02 = new JTable(this.gornjaTable.getData(), this.getGornjaTable().getColumns());

        }

        public void initialiseLookAndFeel() {
            try {
                UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
                SwingUtilities.updateComponentTreeUI(this);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        public JTabbedPane getTabbedPane()
        {
            return tabbedPane;
        }

        public void setTabbedPane(JTabbedPane tabbedPane)
        {
            this.tabbedPane = tabbedPane;
        }

        public ModelStorage getModelStorage() {
            return modelStorage;
        }

        public void setModelStorage(ModelStorage modelStorage) {
            this.modelStorage = modelStorage;
        }

        public NodeStorage getNodeStorage() {
            return nodeStorage;
        }

        public void setNodeStorage(NodeStorage nodeStorage) {
            this.nodeStorage = nodeStorage;
        }

        public ViewToolBar getToolBar() {
            return toolBar;
        }

        public void setToolBar(ViewToolBar toolBar) {
            this.toolBar = toolBar;
        }

        public ViewOurMenuBar getOurMenuBar() {
            return ourMenuBar;
        }

        public void setOurMenuBar(ViewOurMenuBar ourMenuBar) {
            this.ourMenuBar = ourMenuBar;
        }

        public ViewTree getViewTree() {
            return viewTree;
        }

        public void setViewTree(ViewTree viewTree) {
            this.viewTree = viewTree;
        }

        public ViewTable getGornjaTable() {
            return gornjaTable;
        }

        public void setGornjaTable(ViewTable gornjaTable) {
            this.gornjaTable = gornjaTable;
        }

        public ViewTable getDonjaTable() {
            return donjaTable;
        }

        public void setDonjaTable(ViewTable donjaTable) {
            this.donjaTable = donjaTable;
        }

        public JPanel getPanelUp() {
            return panelUp;
        }

        public void setPanelUp(JPanel panelUp) {
            this.panelUp = panelUp;
        }

        public ViewToolBar getTableUpToolBar() {
            return tableUpToolBar;
        }

        public void setTableUpToolBar(ViewToolBar tableUpToolBar) {
            this.tableUpToolBar = tableUpToolBar;
        }

        public JPanel getPanelDown() {
            return panelDown;
        }

        public void setPanelDown(JPanel panelDown) {
            this.panelDown = panelDown;
        }

        /*
        @Override
        public void valueChanged(TreeSelectionEvent event) {
            // TODO Auto-generated method stub
            TreePath path = event.getPath();

            for(int i = 0; i < path.getPathCount(); i++) {
                if(path.getPathComponent(i) instanceof NodeEntity) {
                    this.setNe((NodeEntity)path.getPathComponent(i));
                    this.setModelEntity(this.getNe().getModelEntity());
                    System.out.println("Selektovan dijagram:"+getNe()); 
                    System.out.println("getPath: "+event.getPath());
                    initialiseGornjaTable();
    //              System.out.println("Initialise gornja tabela");

                    boolean jeri = false;
                    for(int br = 0 ; br < tabbedPane.getTabCount(); br++) {
                        //System.out.println("U FORU " + br);
                        //System.out.println(tabbedPane.getTitleAt(br));
                        if(tabbedPane.getTitleAt(br).equals(modelEntity.getName())) {
                            jeri = true;
                        }
                    }
                    if(!jeri) {
                        scrollTb1 = new JScrollPane(getTblStudenti());
                        tabbedPane.addTab(modelEntity.getName(), scrollTb1);
                    }

                    break;
                }
            }

            //scrollTb2.add(tblStudenti02);

            splitTables.setOrientation(JSplitPane.VERTICAL_SPLIT);
            splitTables.setLeftComponent(tabbedPane);
            splitTables.setRightComponent(tblStudenti02);
            splitTables.setDividerLocation(300);

            //split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, scrollPane, split2);
            split.setOrientation(JSplitPane.HORIZONTAL_SPLIT);
            split.setLeftComponent(scrollPane);
            split.setRightComponent(splitTables);
            this.add(split, BorderLayout.CENTER);

            this.revalidate();
                */
        public JTable getTblStudenti02()
        {
            return tblStudenti02;
        }

        public void setTblStudenti02(JTable tblStudenti02)
        {
            this.tblStudenti02 = tblStudenti02;
        }

        public JSplitPane getSplitTables()
        {
            return splitTables;
        }

        public void setSplitTables(JSplitPane splitTables)
        {
            this.splitTables = splitTables;
        }

        public void setSplit(JSplitPane split)
        {
            this.split = split;
        }

        public NodeEntity getNe() {
            return ne;
        }

        public void setNe(NodeEntity ne) {
            this.ne = ne;
        }

        public ModelEntity getModelEntity() {
            return modelEntity;
        }

        public void setModelEntity(ModelEntity modelEntity) {
            this.modelEntity = modelEntity;
        }

        public JTable getTblStudenti() {
            return tblStudenti;
        }

        public void setTblStudenti(JTable tblStudenti) {
            this.tblStudenti = tblStudenti;
        }

        public JScrollPane getScrollTb2()
        {
            return scrollTb2;
        }

        public void setScrollTb2(JScrollPane scrollTb2)
        {
            this.scrollTb2 = scrollTb2;
        }
        public JScrollPane getScrollPane()
        {
            return scrollPane;
        }

        public void setScrollPane(JScrollPane scrollPane)
        {
            this.scrollPane = scrollPane;
        }

        public String getPathMetaschema()
        {
            return pathMetaschema;
        }

        public void setPathMetaschema(String pathMetaschema)
        {
            this.pathMetaschema = pathMetaschema;
        }

        public JTree getJtree() {
            return jtree;
        }

        public void setJtree(JTree jtree) {
            this.jtree = jtree;
        }



    }

我希望有人会对此有所回答。 我真的不喜欢做GUI,尤其不是Swing, 我是一个后端人。

谢谢你们! :)

1 个答案:

答案 0 :(得分:0)

setJtree(new JTree(this.getViewTree()));

不要创建新的JTree。创建JTree不会将组件添加到框架中。

相反,您希望用新的TreeModel替换现有JTree的TreeModel:

tree.setModel( ... );

我认为没有必要使用setJTree(...)方法,因为变量引用永远不会改变,只有添加到树中的模型会发生变化。