ツリーのすべてのノードを JPanel に再帰的に描画しようとしています。
次のようになります。
ここでB
、C
、D
、 は の子ですA
。
そして、E
はF
の子ですB
親子関係の出力は正確です。
PARENT: A | x,y: 180, 100...
CHILD: B | x,y: 205, 150
PARENT: B | x,y: 205, 150...
CHILD: E | x,y: 230, 200
PARENT: B | x,y: 205, 150...
CHILD: F | x,y: 230, 200
end
PARENT: A | x,y: 180, 100...
CHILD: C | x,y: 205, 150
PARENT: A | x,y: 180, 100...
CHILD: D | x,y: 205, 150
しかし、x, y
座標はそうではありません...各子のx
場所は他の子の場所と重なっています...したがって、親ごとに1つの子ノードのみが表示されます:
私がしなければならないことは、子のy
新しい行ごとに1回インクリメントする方法を見つけることだと思います...そしてx
、親の子ごとにインクリメントして、それらが単一の行にうまく配置されるようにします...しかし、ノードの座標はリセットされています。
何かご意見は?
コード:
public void paintComponent(Graphics g) {
g.setColor(Color.BLACK);
g.fillRect(0, 0, width, height);
g.setColor(Color.CYAN);
g.fillRect(rootNode.getX(), rootNode.getY(), rootNode.getWidth(), rootNode.getHeight());
paintComponent(g, rootNode);
}
public void paintComponent(Graphics g, Nodes parentNode) {
//keep generating new nodePrintList to load with new Children
ArrayList<Nodes> nodePrintList = new ArrayList<Nodes>();
//base case: end of nodeList
if (nodeList.indexOf(parentNode)==nodeList.size()-1) {
System.out.println("\nend");
}
else {
//traverse nodeList recursively
nodePrintList = getChildren(parentNode);
//loop through and print all children of node n
System.out.println();
for (Nodes child : nodePrintList) {
g.setColor(Color.GREEN);
child.setX(parentNode.getX()+25);
child.setY(parentNode.getY()+50);
g.fillRect(child.getX(), child.getY(), child.getWidth(), child.getHeight());
System.out.print("PARENT: " + parentNode.getValue() + " | x,y: " + parentNode.getX() + ", " + parentNode.getY() + "...\n CHILD: " + child.getValue() + " | x,y: " + child.getX() + ", " + child.getY());
paintComponent(g, child);
}
}
}
getChildren()
親ごとの子のリストを返すメソッド:
//need to pass a new index to getChildren once current node has no more children
public ArrayList<Nodes> getChildren (Nodes n) {
ArrayList<Nodes> childrenList;
childrenList = new ArrayList<Nodes>();
int index = nodeList.indexOf(n);
int col = 0;
while (col < size) {
if (adjMatrix[index][col] == 1) {
childrenList.add(nodeList.get(col));
}
col++;
}
return childrenList;
}