2017-05-01 19 views
-1

Java에서 JSON 파일을 구문 분석 중입니다. Jackson이나 GSON이 아닌 JSON을 정리하십시오. 제 문제는 새로운 .json 파일을로드 할 때 JTree가 새로 고쳐지지 않는다는 것입니다. stackoverflow 및 다른 포럼에서 발견 한 여러 가지 옵션을 시도했지만 솔루션을 찾지 못했습니다.JTree가 새로 고침되지 않고 새로운 JSON을로드 한 후 제어가 작동하지 않습니다.

아래 코드를 작성하겠습니다.

NodeStorage, NodeEntity 등은 DefaultMutableTreeNode를 상속받은 NodeInfo의 하위 클래스입니다.

ViewTree는 DefaultTreeModel을 확장합니다.

특별히 찾아해야

코드 기능은 내가 여기를 작성하고 코드의 나머지 부분 (전체 GUI 클래스가 다른 창에서이 클래스 아래에 기록됩니다) initialiseTree입니다 :

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를하고 싶지 않습니다. 특히 스윙이 아닙니다. 저는 백엔드 녀석입니다.

고마워요! :)

답변

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

새 JTree를 만들지 마십시오. JTree를 작성해도, 컴퍼넌트는 프레임에 추가되지 않습니다.

대신 새 TreeModel를 사용하여 기존의 JTree의하는 TreeModel를 교체하려면 : 변수 참조가 절대 변하지 않을 것이기 때문

tree.setModel(...); 

나는 당신의 setJTree(...) 방법 만 모델이 추가 된 어떤 필요를 보지 않는다 나무가 바뀐다.