我正在制作图形GUI应用程序,其中我有算法,我可以运行模拟来显示最短路径。现在,图表与无向未加权边缘一起工作正常。现在我想要加权边缘。我想要的是能够将重量放在线上。
无论何时放置边,我都有一个将边放入列表的函数。边具有id,source,destination和weight。我有一个返回重量的功能。我想使用getWeight返回重量,然后将其放在边缘。 这是绘制线的代码
private void pnlGraphMouseDragged(java.awt.event.MouseEvent evt) {
if (_selectedNode >= 0) {
if (SwingUtilities.isLeftMouseButton(evt)) {
Image buff = createImage(pnlGraph.getWidth() - 1, pnlGraph.getHeight() - 1);
Graphics buffG = buff.getGraphics();
buffG.drawImage(bufferImage, 0, 0, this);
Point source = locations.get(_selectedNode);
//buffG.drawLine(source.x, source.y,
//evt.getX(), evt.getY());
drawArrow(buffG, source.x, source.y, evt.getX(), evt.getY());
pnlGraph.getGraphics().drawImage(buff, 1, 1, this);
} else if (SwingUtilities.isMiddleMouseButton(evt)) {
locations.get(_selectedNode).x = evt.getX();
locations.get(_selectedNode).y = evt.getY();
graph();
changesMade = true;
}
}
}
放置边缘后,我创建一个边缘对象并将其放在列表中
private void pnlGraphMouseReleased(java.awt.event.MouseEvent evt) {
if (_selectedNode >= 0) {
int destination = nodeSelected(evt.getX(), evt.getY());
if (destination >= 0 && destination != _selectedNode) {
addEdge(Edgeid, _selectedNode, destination, (int)(Math.random() * 100));
_selectedNode = -1;
changesMade = true;
Edgeid++;
}
}
graph();
}
private void addEdge(int edgeId, int sourceid, int destid, final int weight) {
Edge newEdge = new Edge(edgeId, vertices.get(sourceid), vertices.get(destid), 0, weight);
edges.add(newEdge);
printlnConsole(newEdge.getId()+" "+newEdge.getSource().getName()+" "+newEdge.getDest().getName()+" "+newEdge.getWeight());
vertices.get(sourceid).vList().add(vertices.get(destid));
vertices.get(destid).vList().add(vertices.get(sourceid));
}