我試圖遞歸地將樹的所有節點繪製到JPanel上。Java - 在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;
}
佈局有點複雜......如果在你的例子'C'中有孩子呢?它們會與'B'的重疊。 –
@tobias_k好的,那麼你知道我可以遞歸地繪製樹的節點嗎? – Growler