我正在尝试将树的所有节点递归地绘制到 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
每个新的子行增加一次......并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;
}