2016-04-03 12 views
3

私はツリー構造をグラフ化するように努力していますが、ノードを入力すると表示されますが、表示されません。Java - repaint()メソッドは一度呼び出されても何も表示されません

ルートを描画するだけで、すべてが削除されます。

はここに私のコードです:

public LinkedList<Node> nodes; 
public Tree tree; 

public TreeViewer() { 

    initComponents(); 
    this.nodes = new LinkedList<>(); 
} 

@Override 
public void paintComponent(Graphics g) { 
    super.paintComponent(g); //To change body of generated methods, choose Tools | Templates. 

    if (this.tree != null) { 
     this.checkTree(this.tree.getRoot(), g, 200, 20, 20, 20); 
    }else{ 
     System.out.println("empty"); 
    } 
} 

public void checkTree(Node current, Graphics g, int x, int y, int height, int width) { 

    current.setX(x); 
    current.setY(y); 
    current.setHeight(height); 
    current.setWidth(width); 

    if (!this.nodes.contains(current)) { 
     g.drawString(current.name, x, y); 
     g.setColor(Color.black); 
     this.nodes.add(current); 

     if (current.getSon() != null && current.getBrother() == null) { 
      this.checkTree(current.getSon(), g, x, y + 40, height, width); 

     } else if (current.getBrother() != null && current.getSon() == null) { 
      this.checkTree(current.getBrother(), g, x - 30, y, height, width); 

     } else if (current.getBrother() != null && current.getSon() != null) { 
      this.checkTree(current.getSon(), g, x, y + 40, height, width); 
      this.checkTree(current.getBrother(), g, x - 30, y, height, width); 
     } 
    } 
} 

と私はtroughtノードボタンを追加している、ここでのコードだ:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {           
    if(this.modificator.getTree() == null){ 
     Node current = new Node(JOptionPane.showInputDialog("Type root ID:")); 
     this.modificator.setTree(new Tree(current)); 

    }else{ 
     Node current = new Node(JOptionPane.showInputDialog("Type ID:")); 
     this.modificator.getTree().addSon(this.modificator.getTree().getRoot(), this.modificator.getTree().getRoot(), current); 

    } 
    this.modificator.repaint(); 
} 

だから、私の問題は後に)私は(再描画を呼び出すたびに常駐します最初に、描画されたもの(ルートのみ)がパネルから「消去」されます。 checkTreeインサイド

+0

事前にインスタンス化されたツリーを描画すると機能しますが、実行するたびにノードを追加している間に描画する必要があります。 – JMz

+0

@CameronSkinnerああ... – MadProgrammer

答えて

3

あなたがこの持っている:おそらくこれはあなたのグラフのサイクルを処理することを目的とし

if (!this.nodes.contains(current)) 

を、私はどこでもthis.nodesをクリアしていることがわかりません。つまり、paintComponentへの2回目のコールでは、すぐにthis.nodesにルートが追加されているので、checkTreeからすぐに脱退することになります。

paintComponentの末尾にあるthis.nodesの部分を削除すると、そのトリックを行う可能性があります。

+0

ありがとう!それはそれを解決しました! – JMz

関連する問題