Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 11 of 11

Thread: help for Animated application

  1. #1
    Junior Member
    Join Date
    Dec 2019
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default help for Animated application

    Hello everyone, !! I hope you are well. In fact I am a beginner and i have a java project which consists of finding the shortest path between nodes with a shortest path algorithm. And I had a project in which they implemented it with the Dijkstra algorithm. Indeed, I would like to improve it by bringing it certain keys like the visualization of a packet moving from a source node towards a destination node by following the shortest path compute by the algorithm, fragment and gather the nodes according to certain protocols. Also in the program the nodes are colored circles, indeed I would like to replace them by numbered posts which increment when we click to make them appear. Obviously I don't know how to go about managing these events. I would like you to help me have the necessary tools (library, codes) to carry out this project. Please, i am a beginner and programming passionnated, and i don't really know to start, i really want your help. Thank you.

  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: help for Animated application

    Can you post your code (be sure to wrap in code tags)
    and any specific java programming questions you have.

    Your description of the project sounds like you need to do lots of design work that lists the details of the changes you want to make. The more details the better.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    Dec 2019
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: help for Animated application

    i don't know how to importcodes and project on this forum. can you help me??

  4. #4
    Junior Member
    Join Date
    Dec 2019
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: help for Animated application

    these are the differents parts of the project

    the nodes class:

    package models;

    import java.awt.*;
    import java.util.*;
    import java.util.List;

    public class Node {
    private Point coord = new Point();
    private int id;
    private java.util.List<Node> path;

    public Node(){}

    public Node(int id){
    this.id = id;
    }

    public Node(Point p){
    this.coord = p;
    }

    public void setId(int id){
    this.id = id;
    }

    public void setCoord(int x, int y){
    coord.setLocation(x, y);
    }

    public Point getCoord(){
    return coord;
    }

    public void setPath(List<Node> path) {
    this.path = path;
    }

    public List<Node> getPath() {
    return path;
    }

    public int getX(){
    return (int) coord.getX();
    }

    public int getY(){
    return (int) coord.getY();
    }

    public int getId(){
    return id;
    }

    @Override
    public String toString() {
    return "Node " + id;
    }
    }
    --------------------------------------------------------------------------------------------------------------------------------

    this is the graph class:

    package models;

    import java.awt.*;
    import java.util.ArrayList;
    import java.util.List;

    public class Graph {
    private int count = 1;
    private List<Node> nodes = new ArrayList<>();
    private List<Edge> edges = new ArrayList<>();

    private Node source;
    private Node destination;

    private boolean solved = false;

    public void setSolved(boolean solved) {
    this.solved = solved;
    }

    public boolean isSolved() {
    return solved;
    }

    public void setNodes(List<Node> nodes){
    this.nodes = nodes;
    }

    public List<Node> getNodes(){
    return nodes;
    }

    public void setEdges(List<Edge> edges){
    this.edges = edges;
    }

    public List<Edge> getEdges(){
    return edges;
    }

    public boolean isNodeReachable(Node node){
    for(Edge edge : edges)
    if(node == edge.getNodeOne() || node == edge.getNodeTwo())
    return true;

    return false;
    }

    public void setSource(Node node){
    if(nodes.contains(node))
    source = node;
    }

    public void setDestination(Node node){
    if(nodes.contains(node))
    destination = node;
    }

    public Node getSource(){
    return source;
    }

    public Node getDestination(){
    return destination;
    }

    public boolean isSource(Node node){
    return node == source;
    }

    public boolean isDestination(Node node){
    return node == destination;
    }

    public void addNode(Point coord){
    Node node = new Node(coord);
    addNode(node);
    }

    public void addNode(Node node){
    node.setId(count++);
    nodes.add(node);
    if(node.getId()==1)
    source = node;
    }

    public void addEdge(Edge new_edge){
    boolean added = false;
    for(Edge edge : edges){
    if(edge.equals(new_edge)){
    added = true;
    break;
    }
    }
    if(!added)
    edges.add(new_edge);
    }

    public void deleteNode(Node node){
    List<Edge> delete = new ArrayList<>();
    for (Edge edge : edges){
    if(edge.hasNode(node)){
    delete.add(edge);
    }
    }
    for (Edge edge : delete){
    edges.remove(edge);
    }
    nodes.remove(node);
    }

    public void clear(){
    count = 1;
    nodes.clear();
    edges.clear();
    solved = false;

    source = null;
    destination = null;
    }

    }
    --------------------------------------------------------------------------------------------------------------------------------------

    this is the edge class:

    package models;

    public class Edge {
    private Node one;
    private Node two;
    private int weight = 1;

    public Edge(Node one, Node two){
    this.one = one;
    this.two = two;
    }

    public Node getNodeOne(){
    return one;
    }

    public Node getNodeTwo(){
    return two;
    }

    public void setWeight(int weight){
    this.weight = weight;
    }

    public int getWeight(){
    return weight;
    }

    public boolean hasNode(Node node){
    return one==node || two==node;
    }

    public boolean equals(Edge edge) {
    return (one ==edge.one && two ==edge.two) || (one ==edge.two && two ==edge.one) ;
    }

    @Override
    public String toString() {
    return "Edge ~ "
    + getNodeOne().getId() + " - "
    + getNodeTwo().getId();
    }
    }
    -------------------------------------------------------------------------------------------------------------------------------------

    MainWindow.java class

    package gui;

    import algo.DijkstraAlgorithm;
    import models.Graph;

    import javax.imageio.ImageIO;
    import javax.swing.*;
    import javax.swing.border.EmptyBorder;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.IOException;

    public class MainWindow extends JPanel {

    private Graph graph;
    private GraphPanel graphPanel;

    public MainWindow(){
    super.setLayout(new BorderLayout());
    setGraphPanel();
    }

    private void setGraphPanel(){
    graph = new Graph();
    graphPanel = new GraphPanel(graph);
    graphPanel.setPreferredSize(new Dimension(9000, 4096));

    JScrollPane scroll = new JScrollPane();
    scroll.setViewportView(graphPanel);
    scroll.setPreferredSize(new Dimension(750, 500));
    scroll.getViewport().setViewPosition(new Point(4100, 0));
    add(scroll, BorderLayout.CENTER);
    setTopPanel();
    setButtons();
    }

    private void setTopPanel() {
    JLabel info = new JLabel("Algorithme de Routage");
    info.setForeground(new Color(230, 220, 250));
    JPanel panel = new JPanel();
    panel.setBackground(new Color(130, 50, 250));
    panel.add(info);
    panel.setBorder(new EmptyBorder(5, 5, 5, 5));
    add(panel, BorderLayout.NORTH);
    }

    private void setButtons(){
    JButton run = new JButton();
    setupIcon(run, "run");
    JButton reset = new JButton();
    setupIcon(reset, "reset");
    final JButton info = new JButton();
    setupIcon(info, "info");

    JPanel buttonPanel = new JPanel();
    buttonPanel.setBackground(DrawUtils.parseColor("#D DDDDD"));
    buttonPanel.add(reset);
    buttonPanel.add(run);
    buttonPanel.add(info);

    reset.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
    graphPanel.reset();
    }
    });

    info.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
    JOptionPane.showMessageDialog(null,
    "Click on empty space to create new node\n" +
    "Drag from node to node to create an edge\n" +
    "Click on edges to set the weight\n\n" +
    "Combinations:\n" +
    "Shift + D Click : Set node as source\n" +
    "Shift + S Click : Set node as destination\n" +
    "Ctrl + Drag : Reposition Node\n" +
    "Ctrl + Click : Get Path of Node\n" +
    "Ctrl + Shift + Click : Delete Node/Edge\n");
    }
    });

    run.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
    DijkstraAlgorithm dijkstraAlgorithm = new DijkstraAlgorithm(graph);
    try{
    dijkstraAlgorithm.run();
    graphPanel.setPath(dijkstraAlgorithm.getDestinatio nPath());
    } catch (IllegalStateException ise){
    JOptionPane.showMessageDialog(null, ise.getMessage());
    }
    }
    });

    add(buttonPanel, BorderLayout.SOUTH);
    }

    private void setupIcon(JButton button, String img){
    try {
    Image icon = ImageIO.read(getClass().getResource(
    "/resources/" + img + ".png"));
    ImageIcon imageIcon = new ImageIcon(icon);
    button.setIcon(imageIcon);
    button.setBorderPainted(false);
    button.setFocusPainted(false);
    button.setContentAreaFilled(false);
    } catch (IOException e) {
    e.printStackTrace();
    }
    }

    }
    -------------------------------------------------------------------------------------------------------------------------

    the graphPanel.java class

    package gui;

    import models.Edge;
    import models.Graph;
    import models.Node;

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseMotionListener;
    import java.util.*;
    import java.util.List;


    public class GraphPanel extends JPanel implements MouseListener, MouseMotionListener {

    private DrawUtils drawUtils;

    private Graph graph;

    private Node selectedNode = null;
    private Node hoveredNode = null;
    private Edge hoveredEdge = null;

    private java.util.List<Node> path = null;

    private Point cursor;

    public GraphPanel(Graph graph){
    this.graph = graph;

    addMouseListener(this);
    addMouseMotionListener(this);
    }

    public void setPath(List<Node> path) {
    this.path = path;
    hoveredEdge = null;
    repaint();
    }

    @Override
    protected void paintComponent(Graphics g) {
    super.paintComponent(g);

    Graphics2D graphics2d = (Graphics2D) g;
    graphics2d.setRenderingHint(RenderingHints.KEY_ANT IALIASING,
    RenderingHints.VALUE_ANTIALIAS_ON);
    graphics2d.setRenderingHint(RenderingHints.KEY_TEX T_ANTIALIASING,
    RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

    drawUtils = new DrawUtils(graphics2d);

    if(graph.isSolved()){
    drawUtils.drawPath(path);
    }

    if(selectedNode != null && cursor != null){
    Edge e = new Edge(selectedNode, new Node(cursor));
    drawUtils.drawEdge(e);
    }

    for(Edge edge : graph.getEdges()){
    if(edge == hoveredEdge)
    drawUtils.drawHoveredEdge(edge);
    drawUtils.drawEdge(edge);
    }

    for(Node node : graph.getNodes()){
    if(node == selectedNode || node == hoveredNode)
    drawUtils.drawHalo(node);
    if(graph.isSource(node))
    drawUtils.drawSourceNode(node);
    else if(graph.isDestination(node))
    drawUtils.drawDestinationNode(node);
    else
    drawUtils.drawNode(node);
    }
    }

    @Override
    public void mouseClicked(MouseEvent e) {

    Node selected = null;
    for(Node node : graph.getNodes()) {
    if(DrawUtils.isWithinBounds(e, node.getCoord())){
    selected = node;
    break;
    }
    }

    if(selected!=null) {
    if(e.isControlDown() && e.isShiftDown()){
    graph.deleteNode(selected);
    graph.setSolved(false);
    repaint();
    return;
    } else if(e.isControlDown() && graph.isSolved()){
    path = selected.getPath();
    repaint();
    return;
    } else if(e.isShiftDown()){
    if(SwingUtilities.isLeftMouseButton(e)){
    if(!graph.isDestination(selected))
    graph.setSource(selected);
    else
    JOptionPane.showMessageDialog(null, "Destination can't be set as Source");
    } else if(SwingUtilities.isRightMouseButton(e)) {
    if(!graph.isSource(selected))
    graph.setDestination(selected);
    else
    JOptionPane.showMessageDialog(null, "Source can't be set as Destination");
    }else
    return;

    graph.setSolved(false);
    repaint();
    return;
    }
    }

    if(hoveredEdge!=null){
    if(e.isControlDown() && e.isShiftDown()){
    graph.getEdges().remove(hoveredEdge);
    hoveredEdge = null;
    graph.setSolved(false);
    repaint();
    return;
    }

    String input = JOptionPane.showInputDialog("Enter weight for " + hoveredEdge.toString()
    + " : ");
    try {
    int weight = Integer.parseInt(input);
    if (weight > 0) {
    hoveredEdge.setWeight(weight);
    graph.setSolved(false);
    repaint();
    } else {
    JOptionPane.showMessageDialog(null, "Weight should be positive");
    }
    } catch (NumberFormatException nfe) {}
    return;
    }

    for(Node node : graph.getNodes()) {
    if(DrawUtils.isOverlapping(e, node.getCoord())){
    JOptionPane.showMessageDialog(null, "Overlapping Node can't be created");
    return;
    }
    }

    graph.addNode(e.getPoint());
    graph.setSolved(false);
    repaint();
    }

    @Override
    public void mousePressed(MouseEvent e) {

    }

    @Override
    public void mouseReleased(MouseEvent e) {
    for (Node node : graph.getNodes()) {
    if(selectedNode !=null && node!= selectedNode && DrawUtils.isWithinBounds(e, node.getCoord())){
    Edge new_edge = new Edge(selectedNode, node);
    graph.addEdge(new_edge);
    graph.setSolved(false);
    }
    }
    selectedNode = null;
    hoveredNode = null;
    repaint();
    }

    @Override
    public void mouseEntered(MouseEvent e) {

    }

    @Override
    public void mouseExited(MouseEvent e) {

    }

    @Override
    public void mouseDragged(MouseEvent e) {
    hoveredNode = null;

    for (Node node : graph.getNodes()) {
    if(selectedNode ==null && DrawUtils.isWithinBounds(e, node.getCoord())){
    selectedNode = node;
    } else if(DrawUtils.isWithinBounds(e, node.getCoord())) {
    hoveredNode = node;
    }
    }

    if(selectedNode !=null){
    if(e.isControlDown()){
    selectedNode.setCoord(e.getX(), e.getY());
    cursor = null;
    repaint();
    return;
    }

    cursor = new Point(e.getX(), e.getY());
    repaint();
    }
    }

    @Override
    public void mouseMoved(MouseEvent e) {

    if(e.isControlDown()){
    hoveredNode = null;
    for (Node node : graph.getNodes()) {
    if(DrawUtils.isWithinBounds(e, node.getCoord())) {
    hoveredNode = node;
    }
    }
    }

    hoveredEdge = null;

    for (Edge edge : graph.getEdges()) {
    if(DrawUtils.isOnEdge(e, edge)) {
    hoveredEdge = edge;
    }
    }

    repaint();
    }

    public void reset(){
    graph.clear();
    selectedNode = null;
    hoveredNode = null;
    hoveredEdge = null;
    repaint();
    }
    }
    ----------------------------------------------------------------------------------------------------------------------------

    Drawutils.java class

    package gui;

    import models.Edge;
    import models.Node;

    import java.awt.*;
    import java.awt.event.MouseEvent;
    import java.util.*;
    import java.util.List;

    public class DrawUtils {
    private Graphics2D g;
    private static int radius = 20;

    public DrawUtils(Graphics2D graphics2D){
    g = graphics2D;
    }

    public static boolean isWithinBounds(MouseEvent e, Point p) {
    int x = e.getX();
    int y = e.getY();

    int boundX = (int) p.getX();
    int boundY = (int) p.getY();

    return (x <= boundX + radius && x >= boundX - radius) && (y <= boundY + radius && y >= boundY - radius);
    }

    public static boolean isOverlapping(MouseEvent e, Point p) {
    int x = e.getX();
    int y = e.getY();

    int boundX = (int) p.getX();
    int boundY = (int) p.getY();

    return (x <= boundX + 2.5*radius && x >= boundX - 2.5*radius) && (y <= boundY + 2.5*radius && y >= boundY - 2.5*radius);
    }

    public static boolean isOnEdge(MouseEvent e, Edge edge) {

    int dist = distToSegment( e.getPoint(),
    edge.getNodeOne().getCoord(),
    edge.getNodeTwo().getCoord() );
    if (dist<6)
    return true;
    return false;
    }

    public static Color parseColor(String colorStr) {
    return new Color(
    Integer.valueOf(colorStr.substring(1, 3), 16),
    Integer.valueOf(colorStr.substring(3, 5), 16),
    Integer.valueOf(colorStr.substring(5, 7), 16));
    }

    public void drawWeight(Edge edge) {
    Point from = edge.getNodeOne().getCoord();
    Point to = edge.getNodeTwo().getCoord();
    int x = (from.x + to.x)/2;
    int y = (from.y + to.y)/2;

    int rad = radius/2;
    g.fillOval(x-rad, y-rad, 2*rad, 2*rad);
    drawWeightText(String.valueOf(edge.getWeight()), x, y);
    }

    public void drawPath(java.util.List<Node> path) {
    List<Edge> edges = new ArrayList<>();
    for(int i = 0; i < path.size()-1; i++) {
    edges.add(new Edge(path.get(i), path.get(i+1)));
    }

    for(Edge edge : edges) {
    drawPath(edge);
    }
    }

    public void drawPath(Edge edge) {
    g.setColor(parseColor("#00BCD4"));
    drawBoldEdge(edge);
    }

    public void drawHoveredEdge(Edge edge) {
    g.setColor(parseColor("#E1BEE7"));
    drawBoldEdge(edge);
    }

    private void drawBoldEdge(Edge edge){
    Point from = edge.getNodeOne().getCoord();
    Point to = edge.getNodeTwo().getCoord();
    g.setStroke(new BasicStroke(8));
    g.drawLine(from.x, from.y, to.x, to.y);
    int x = (from.x + to.x)/2;
    int y = (from.y + to.y)/2;

    int rad = 13;
    g.fillOval(x-rad, y-rad, 2*rad, 2*rad);
    }

    public void drawEdge(Edge edge) {
    g.setColor(parseColor("#555555"));
    drawBaseEdge(edge);
    drawWeight(edge);
    }

    private void drawBaseEdge(Edge edge){
    Point from = edge.getNodeOne().getCoord();
    Point to = edge.getNodeTwo().getCoord();
    g.setStroke(new BasicStroke(3));
    g.drawLine(from.x, from.y, to.x, to.y);
    }

    public void drawHalo(Node node){
    g.setColor(parseColor("#E91E63"));
    radius+=5;
    g.fillOval(node.getX() - radius, node.getY() - radius, 2 * radius, 2 * radius);
    radius-=5;
    }

    public void drawSourceNode(Node node){
    g.setColor(parseColor("#00BCD4"));
    g.fillOval(node.getX() - radius, node.getY() - radius, 2 * radius, 2 * radius);

    radius-=5;
    g.setColor(parseColor("#B2EBF2"));
    g.fillOval(node.getX() - radius, node.getY() - radius, 2 * radius, 2 * radius);

    radius+=5;
    g.setColor(parseColor("#00BCD4"));
    drawCentreText(String.valueOf(node.getId()), node.getX(), node.getY());
    }

    public void drawDestinationNode(Node node){
    g.setColor(parseColor("#F44336"));
    g.fillOval(node.getX() - radius, node.getY() - radius, 2 * radius, 2 * radius);

    radius-=5;
    g.setColor(parseColor("#FFCDD2"));
    g.fillOval(node.getX() - radius, node.getY() - radius, 2 * radius, 2 * radius);

    radius+=5;
    g.setColor(parseColor("#F44336"));
    drawCentreText(String.valueOf(node.getId()), node.getX(), node.getY());
    }

    public void drawNode(Node node){
    g.setColor(parseColor("#9C27B0"));
    g.fillOval(node.getX() - radius, node.getY() - radius, 2 * radius, 2 * radius);

    radius-=5;
    g.setColor(parseColor("#E1BEE7"));
    g.fillOval(node.getX() - radius, node.getY() - radius, 2 * radius, 2 * radius);

    radius+=5;
    g.setColor(parseColor("#9C27B0"));
    drawCentreText(String.valueOf(node.getId()), node.getX(), node.getY());
    }

    public void drawWeightText(String text, int x, int y) {
    g.setColor(parseColor("#cccccc"));
    FontMetrics fm = g.getFontMetrics();
    double t_width = fm.getStringBounds(text, g).getWidth();
    g.drawString(text, (int) (x - t_width / 2), (y + fm.getMaxAscent() / 2));
    }

    public void drawCentreText(String text, int x, int y) {
    FontMetrics fm = g.getFontMetrics();
    double t_width = fm.getStringBounds(text, g).getWidth();
    g.drawString(text, (int) (x - t_width / 2), (y + fm.getMaxAscent() / 2));
    }


    // Calculations
    private static int sqr(int x) {
    return x * x;
    }
    private static int dist2(Point v, Point w) {
    return sqr(v.x - w.x) + sqr(v.y - w.y);
    }
    private static int distToSegmentSquared(Point p, Point v, Point w) {
    double l2 = dist2(v, w);
    if (l2 == 0) return dist2(p, v);
    double t = ((p.x - v.x) * (w.x - v.x) + (p.y - v.y) * (w.y - v.y)) / l2;
    if (t < 0) return dist2(p, v);
    if (t > 1) return dist2(p, w);
    return dist2(p, new Point(
    (int)(v.x + t * (w.x - v.x)),
    (int)(v.y + t * (w.y - v.y))
    ));
    }
    private static int distToSegment(Point p, Point v, Point w) {
    return (int) Math.sqrt(distToSegmentSquared(p, v, w));
    }

    }
    --------------------------------------------------------------------------------------------------------------------------------------

    DijkstraAlgorithm.java class

    package algo;

    import models.Edge;
    import models.Graph;
    import models.Node;

    import java.util.*;

    public class DijkstraAlgorithm {
    private boolean safe = false;
    private String message = null;

    private Graph graph;
    private Map<Node, Node> predecessors;
    private Map<Node, Integer> distances;

    private PriorityQueue<Node> unvisited;
    private HashSet<Node> visited;

    public class NodeComparator implements Comparator<Node> {
    @Override
    public int compare(Node node1, Node node2) {
    return distances.get(node1) - distances.get(node2);
    }
    };

    public DijkstraAlgorithm(Graph graph){
    this.graph = graph;
    predecessors = new HashMap<>();
    distances = new HashMap<>();

    for(Node node : graph.getNodes()){
    distances.put(node, Integer.MAX_VALUE);
    }
    visited = new HashSet<>();

    safe = evaluate();
    }

    private boolean evaluate(){
    if(graph.getSource()==null){
    message = "Source must be present in the graph";
    return false;
    }

    if(graph.getDestination()==null){
    message = "Destination must be present in the graph";
    return false;
    }

    for(Node node : graph.getNodes()){
    if(!graph.isNodeReachable(node)){
    message = "Graph contains unreachable nodes";
    return false;
    }
    }

    return true;
    }

    public void run() throws IllegalStateException {
    if(!safe) {
    throw new IllegalStateException(message);
    }

    unvisited = new PriorityQueue<>(graph.getNodes().size(), new NodeComparator());

    Node source = graph.getSource();
    distances.put(source, 0);
    visited.add(source);

    for (Edge neighbor : getNeighbors(source)){
    Node adjacent = getAdjacent(neighbor, source);
    if(adjacent==null)
    continue;

    distances.put(adjacent, neighbor.getWeight());
    predecessors.put(adjacent, source);
    unvisited.add(adjacent);
    }

    while (!unvisited.isEmpty()){
    Node current = unvisited.poll();

    updateDistance(current);

    unvisited.remove(current);
    visited.add(current);
    }

    for(Node node : graph.getNodes()) {
    node.setPath(getPath(node));
    }

    graph.setSolved(true);

    }

    private void updateDistance(Node node){
    int distance = distances.get(node);

    for (Edge neighbor : getNeighbors(node)){
    Node adjacent = getAdjacent(neighbor, node);
    if(visited.contains(adjacent))
    continue;

    int current_dist = distances.get(adjacent);
    int new_dist = distance + neighbor.getWeight();

    if(new_dist < current_dist) {
    distances.put(adjacent, new_dist);
    predecessors.put(adjacent, node);
    unvisited.add(adjacent);
    }
    }
    }

    private Node getAdjacent(Edge edge, Node node) {
    if(edge.getNodeOne()!=node && edge.getNodeTwo()!=node)
    return null;

    return node==edge.getNodeTwo()?edge.getNodeOne():edge.get NodeTwo();
    }

    private List<Edge> getNeighbors(Node node) {
    List<Edge> neighbors = new ArrayList<>();

    for(Edge edge : graph.getEdges()){
    if(edge.getNodeOne()==node ||edge.getNodeTwo()==node)
    neighbors.add(edge);
    }

    return neighbors;
    }

    public Integer getDestinationDistance(){
    return distances.get(graph.getDestination());
    }

    public Integer getDistance(Node node){
    return distances.get(node);
    }

    public List<Node> getDestinationPath() {
    return getPath(graph.getDestination());
    }

    public List<Node> getPath(Node node){
    List<Node> path = new ArrayList<>();

    Node current = node;
    path.add(current);
    while (current!=graph.getSource()){
    current = predecessors.get(current);
    path.add(current);
    }

    Collections.reverse(path);

    return path;
    }

    }
    -------------------------------------------------------------------------------------------------------------------

    Main.java class:

    import gui.MainWindow;

    import javax.swing.*;
    import java.awt.*;

    public class Main {

    public static void main(String[] args)
    {
    try
    {
    UIManager.setLookAndFeel(UIManager.getSystemLookAn dFeelClassName());
    } catch (Exception e) { }

    JFrame j = new JFrame();
    j.setTitle("Dijkstra Algorithm");

    j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    j.setSize(new Dimension(900, 600));
    j.add(new MainWindow());
    j.setVisible(true);

    }

    }
    --------------------------------------------------------------------------------------------------------------------------------


    All the classes are there you can check...

  5. #5
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: help for Animated application

    Please edit your post and wrap your code with code tags:

    [code]
    **YOUR CODE GOES HERE**
    [/code]

    to get highlighting and preserve formatting.

    Can you post details on what changes you are trying to make to the program?
    What does the program do now?
    What do you want it to do?

    You need to work out the details for what the program needs to do to solve your program.

    --- Update ---

    There are NO comments in the code describing what it does and how it works.

    I do not like working with code that does not have comments.
    If you don't understand my answer, don't ignore it, ask a question.

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: help for Animated application

    A suggestion: Add code to load a path so a tester does not need to do that step and so that all testers will be working with the same path.
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Junior Member
    Join Date
    Dec 2019
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: help for Animated application

    Really, i don't know how to do that

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: help for Animated application

    It would be done in the main() method.
    Build a path by calling the methods to add nodes, connect the nodes with edges and set the start and destination nodes. You may have to add a method here and there to allow it all to be done.
    The objective would be for the code in the main method to build a full path to be used for testing the changes you want to make.

    For example:
            Node n1 = new Node(new Point(4300, 100));
            graph.addNode(n1);
            Node n2 = new Node(new Point(4400, 200));
            graph.addNode(n2);
            Edge new_edge = new Edge(n1, n2);
            graph.addEdge(new_edge);
            graph.setDestination(n2);
    If you don't understand my answer, don't ignore it, ask a question.

  9. #9
    Junior Member
    Join Date
    Dec 2019
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: help for Animated application

    THE CODE OF PROJECT WITH THE TAG
    --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    Node class

    package models;

    import java.awt.*;
    import java.util.*;
    import java.util.List;

    //Draw a node on the screen

    public class Node
    {
    private Point coord = new Point(); // An instance of Point
    private int id;
    private java.util.List<Node> path;

    public Node(){}

    // Initialization of The node id
    public Node(int id)
    {
    this.id = id;
    }

    // Initialization of reference point
    public Node(Point p)
    {
    this.coord = p; // Initialization of reference point
    }

    //Set node id
    public void setId(int id)
    {
    this.id = id;
    }


    //Set a node location
    public void setCoord(int x, int y){
    coord.setLocation(x, y);
    }

    //Get a Node reference
    public Point getCoord(){
    return coord;
    }


    //Set a node path
    public void setPath(List<Node> path) {
    this.path = path;
    }

    //Get a node path
    public List<Node> getPath() {
    return path;
    }


    //get the abscissa reference
    public int getX(){
    return (int) coord.getX();
    }

    //Get the reference on the y-axis
    public int getY(){
    return (int) coord.getY();
    }


    //get the id
    public int getId(){
    return id;
    }

    //Write the Node and the id
    public String toString() {
    return "Node " + id;
    }
    }
    ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    The graph class

    package models;

    import java.awt.*;
    import java.util.ArrayList;
    import java.util.List;

    //Drawing the Graph

    public class Graph
    {
    private int count = 1;
    private List<Node> nodes = new ArrayList<>();
    private List<Edge> edges = new ArrayList<>();

    private Node source;
    private Node destination;

    private boolean solved = false;

    public void setSolved(boolean solved)
    {
    this.solved = solved;
    }

    public boolean isSolved()
    {
    return solved;
    }

    //Set the list of Node
    public void setNodes(List<Node> nodes){
    this.nodes = nodes;
    }

    //Get the list of Node
    public List<Node> getNodes()
    {
    return nodes;
    }

    //Set the list of Edge
    public void setEdges(List<Edge> edges)
    {
    this.edges = edges;
    }

    //Get the list of Edge
    public List<Edge> getEdges()
    {
    return edges;
    }

    //Checking if two nodes are reachable
    public boolean isNodeReachable(Node node)
    {
    for(Edge edge : edges)
    if(node == edge.getNodeOne() || node == edge.getNodeTwo())
    return true;

    return false;
    }

    //Set a source Node
    public void setSource(Node node)
    {
    if(nodes.contains(node))
    source = node;
    }

    //Set a Destination Node
    public void setDestination(Node node)
    {
    if(nodes.contains(node))
    destination = node;
    }

    //Get the source Node
    public Node getSource()
    {
    return source;
    }

    //Get the destination Node
    public Node getDestination()
    {
    return destination;
    }

    //Checking if the node is source
    public boolean isSource(Node node)
    {
    return node == source;
    }

    //Checking if the Node is Destination
    public boolean isDestination(Node node)
    {
    return node == destination;
    }

    public void addNode(Point coord){
    Node node = new Node(coord);
    addNode(node);
    }

    //Adding of a Node
    public void addNode(Node node)
    {
    node.setId(count++);
    nodes.add(node);
    if(node.getId()==1)
    source = node;
    }

    //Adding of an Edge
    public void addEdge(Edge new_edge)
    {
    boolean added = false;
    for(Edge edge : edges){
    if(edge.equals(new_edge)){
    added = true;
    break;
    }
    }
    if(!added)
    edges.add(new_edge);
    }
    //Delete a Node
    public void deleteNode(Node node)
    {
    List<Edge> delete = new ArrayList<>();
    for (Edge edge : edges){
    if(edge.hasNode(node)){
    delete.add(edge);
    }
    }
    for (Edge edge : delete){
    edges.remove(edge);
    }
    nodes.remove(node);
    }

    // Clear the Screen
    public void clear()
    {
    count = 1;
    nodes.clear();
    edges.clear();
    solved = false;

    source = null;
    destination = null;
    }

    }
    --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    The edge class

    package models;


    // Drawing edge
    public class Edge
    {
    private Node one;
    private Node two;
    private int weight = 1;

    //Initialization of an Edge
    public Edge(Node one, Node two)
    {
    this.one = one;
    this.two = two;
    }

    //Get the first Node
    public Node getNodeOne()
    {
    return one;
    }

    // Get the second Node
    public Node getNodeTwo()
    {
    return two;
    }

    //Set an edge weight
    public void setWeight(int weight)
    {
    this.weight = weight;
    }

    // get a Weight
    public int getWeight()
    {
    return weight;
    }

    public boolean hasNode(Node node)
    {
    return one==node || two==node;
    }

    public boolean equals(Edge edge)
    {
    return (one ==edge.one && two ==edge.two) || (one ==edge.two && two ==edge.one) ;
    }


    public String toString()
    {
    return "Edge ~ "
    + getNodeOne().getId() + " - "
    + getNodeTwo().getId();
    }
    }
    -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    drawutils class

    package gui;

    import models.Edge;
    import models.Node;

    import java.awt.*;
    import java.awt.event.MouseEvent;
    import java.util.*;
    import java.util.List;


    public class DrawUtils
    {
    private Graphics2D g;
    private static int radius = 20;


    //Initialization of graphic component
    public DrawUtils(Graphics2D graphics2D)
    {
    this.g = graphics2D;
    }


    public static boolean isWithinBounds(MouseEvent e, Point p)
    {
    int x = e.getX();
    int y = e.getY();

    int boundX = (int) p.getX();
    int boundY = (int) p.getY();

    return (x <= boundX + radius && x >= boundX - radius) && (y <= boundY + radius && y >= boundY - radius);
    }

    public static boolean isOverlapping(MouseEvent e, Point p) {
    int x = e.getX();
    int y = e.getY();

    int boundX = (int) p.getX();
    int boundY = (int) p.getY();

    return (x <= boundX + 2.5*radius && x >= boundX - 2.5*radius) && (y <= boundY + 2.5*radius && y >= boundY - 2.5*radius);
    }

    public static boolean isOnEdge(MouseEvent e, Edge edge) {

    int dist = distToSegment( e.getPoint(),
    edge.getNodeOne().getCoord(),
    edge.getNodeTwo().getCoord() );
    if (dist<6)
    return true;
    return false;
    }

    //Drawing color
    public static Color parseColor(String colorStr) {
    return new Color(
    Integer.valueOf(colorStr.substring(1, 3), 16),
    Integer.valueOf(colorStr.substring(3, 5), 16),
    Integer.valueOf(colorStr.substring(5, 7), 16));
    }

    //Drawing weight
    public void drawWeight(Edge edge) {
    Point from = edge.getNodeOne().getCoord();
    Point to = edge.getNodeTwo().getCoord();
    int x = (from.x + to.x)/2;
    int y = (from.y + to.y)/2;

    int rad = radius/2;
    g.fillOval(x-rad, y-rad, 2*rad, 2*rad);
    drawWeightText(String.valueOf(edge.getWeight()), x, y);
    }

    //Draw path between Nodes
    public void drawPath(java.util.List<Node> path) {
    List<Edge> edges = new ArrayList<>();
    for(int i = 0; i < path.size()-1; i++) {
    edges.add(new Edge(path.get(i), path.get(i+1)));
    }

    for(Edge edge : edges) {
    drawPath(edge);
    }
    }


    public void drawPath(Edge edge) {
    g.setColor(parseColor("#00BCD4"));
    drawBoldEdge(edge);
    }

    public void drawHoveredEdge(Edge edge) {
    g.setColor(parseColor("#E1BEE7"));
    drawBoldEdge(edge);
    }

    private void drawBoldEdge(Edge edge){
    Point from = edge.getNodeOne().getCoord();
    Point to = edge.getNodeTwo().getCoord();
    g.setStroke(new BasicStroke(8));
    g.drawLine(from.x, from.y, to.x, to.y);
    int x = (from.x + to.x)/2;
    int y = (from.y + to.y)/2;

    int rad = 13;
    g.fillOval(x-rad, y-rad, 2*rad, 2*rad);
    }

    public void drawEdge(Edge edge) {
    g.setColor(parseColor("#555555"));
    drawBaseEdge(edge);
    drawWeight(edge);
    }

    private void drawBaseEdge(Edge edge){
    Point from = edge.getNodeOne().getCoord();
    Point to = edge.getNodeTwo().getCoord();
    g.setStroke(new BasicStroke(3));
    g.drawLine(from.x, from.y, to.x, to.y);
    }

    public void drawHalo(Node node){
    g.setColor(parseColor("#E91E63"));
    radius+=5;
    g.fillOval(node.getX() - radius, node.getY() - radius, 2 * radius, 2 * radius);
    radius-=5;
    }

    //Draw Source Node
    public void drawSourceNode(Node node){
    g.setColor(parseColor("#00BCD4"));
    g.fillOval(node.getX() - radius, node.getY() - radius, 2 * radius, 2 * radius);

    radius-=5;
    g.setColor(parseColor("#B2EBF2"));
    g.fillOval(node.getX() - radius, node.getY() - radius, 2 * radius, 2 * radius);

    radius+=5;
    g.setColor(parseColor("#00BCD4"));
    drawCentreText(String.valueOf(node.getId()), node.getX(), node.getY());
    }

    // Draw destination Nodes
    public void drawDestinationNode(Node node){
    g.setColor(parseColor("#F44336"));
    g.fillOval(node.getX() - radius, node.getY() - radius, 2 * radius, 2 * radius);

    radius-=5;
    g.setColor(parseColor("#FFCDD2"));
    g.fillOval(node.getX() - radius, node.getY() - radius, 2 * radius, 2 * radius);

    radius+=5;
    g.setColor(parseColor("#F44336"));
    drawCentreText(String.valueOf(node.getId()), node.getX(), node.getY());
    }

    //draw Nodes
    public void drawNode(Node node){
    g.setColor(parseColor("#9C27B0"));
    g.fillOval(node.getX() - radius, node.getY() - radius, 2 * radius, 2 * radius);

    radius-=5;
    g.setColor(parseColor("#E1BEE7"));
    g.fillOval(node.getX() - radius, node.getY() - radius, 2 * radius, 2 * radius);

    radius+=5;
    g.setColor(parseColor("#9C27B0"));
    drawCentreText(String.valueOf(node.getId()), node.getX(), node.getY());
    }

    public void drawWeightText(String text, int x, int y) {
    g.setColor(parseColor("#cccccc"));
    FontMetrics fm = g.getFontMetrics();
    double t_width = fm.getStringBounds(text, g).getWidth();
    g.drawString(text, (int) (x - t_width / 2), (y + fm.getMaxAscent() / 2));
    }

    public void drawCentreText(String text, int x, int y) {
    FontMetrics fm = g.getFontMetrics();
    double t_width = fm.getStringBounds(text, g).getWidth();
    g.drawString(text, (int) (x - t_width / 2), (y + fm.getMaxAscent() / 2));
    }


    // Calculations
    private static int sqr(int x) {
    return x * x;
    }
    private static int dist2(Point v, Point w) {
    return sqr(v.x - w.x) + sqr(v.y - w.y);
    }
    private static int distToSegmentSquared(Point p, Point v, Point w) {
    double l2 = dist2(v, w);
    if (l2 == 0) return dist2(p, v);
    double t = ((p.x - v.x) * (w.x - v.x) + (p.y - v.y) * (w.y - v.y)) / l2;
    if (t < 0) return dist2(p, v);
    if (t > 1) return dist2(p, w);
    return dist2(p, new Point(
    (int)(v.x + t * (w.x - v.x)),
    (int)(v.y + t * (w.y - v.y))
    ));
    }
    private static int distToSegment(Point p, Point v, Point w) {
    return (int) Math.sqrt(distToSegmentSquared(p, v, w));
    }

    }
    -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    graphPanel Class

    package gui;

    import models.Edge;
    import models.Graph;
    import models.Node;

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseMotionListener;
    import java.util.*;
    import java.util.List;

    //Drawing graph Panel

    public class GraphPanel extends JPanel implements MouseListener, MouseMotionListener
    {

    private DrawUtils drawUtils;

    private Graph graph;

    private Node selectedNode = null;
    private Node hoveredNode = null;
    private Edge hoveredEdge = null;

    private java.util.List<Node> path = null;

    private Point cursor;

    //Initialization of graph
    public GraphPanel(Graph graph)
    {
    this.graph = graph;

    addMouseListener(this);
    addMouseMotionListener(this);
    }

    //Set path between nodes
    public void setPath(List<Node> path) {
    this.path = path;
    hoveredEdge = null;
    repaint();
    }

    //paint graphics component
    protected void paintComponent(Graphics g)
    {
    super.paintComponent(g);

    Graphics2D graphics2d = (Graphics2D) g;
    graphics2d.setRenderingHint(RenderingHints.KEY_ANT IALIASING,
    RenderingHints.VALUE_ANTIALIAS_ON);
    graphics2d.setRenderingHint(RenderingHints.KEY_TEX T_ANTIALIASING,
    RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

    drawUtils = new DrawUtils(graphics2d);

    if(graph.isSolved()){
    drawUtils.drawPath(path);
    }

    if(selectedNode != null && cursor != null){
    Edge e = new Edge(selectedNode, new Node(cursor));
    drawUtils.drawEdge(e);
    }

    for(Edge edge : graph.getEdges()){
    if(edge == hoveredEdge)
    drawUtils.drawHoveredEdge(edge);
    drawUtils.drawEdge(edge);
    }

    for(Node node : graph.getNodes()){
    if(node == selectedNode || node == hoveredNode)
    drawUtils.drawHalo(node);
    if(graph.isSource(node))
    drawUtils.drawSourceNode(node);
    else if(graph.isDestination(node))
    drawUtils.drawDestinationNode(node);
    else
    drawUtils.drawNode(node);
    }
    }


    //Mouse action click
    public void mouseClicked(MouseEvent e) {

    Node selected = null;
    for(Node node : graph.getNodes()) {
    if(DrawUtils.isWithinBounds(e, node.getCoord())){
    selected = node;
    break;
    }
    }

    if(selected!=null) {
    if(e.isControlDown() && e.isShiftDown()){
    graph.deleteNode(selected);
    graph.setSolved(false);
    repaint();
    return;
    } else if(e.isControlDown() && graph.isSolved()){
    path = selected.getPath();
    repaint();
    return;
    } else if(e.isShiftDown()){
    if(SwingUtilities.isLeftMouseButton(e)){
    if(!graph.isDestination(selected))
    graph.setSource(selected);
    else
    JOptionPane.showMessageDialog(null, "Destination can't be set as Source");
    } else if(SwingUtilities.isRightMouseButton(e)) {
    if(!graph.isSource(selected))
    graph.setDestination(selected);
    else
    JOptionPane.showMessageDialog(null, "Source can't be set as Destination");
    }else
    return;

    graph.setSolved(false);
    repaint();
    return;
    }
    }

    if(hoveredEdge!=null){
    if(e.isControlDown() && e.isShiftDown()){
    graph.getEdges().remove(hoveredEdge);
    hoveredEdge = null;
    graph.setSolved(false);
    repaint();
    return;
    }

    String input = JOptionPane.showInputDialog("Enter weight for " + hoveredEdge.toString()
    + " : ");
    try {
    int weight = Integer.parseInt(input);
    if (weight > 0) {
    hoveredEdge.setWeight(weight);
    graph.setSolved(false);
    repaint();
    } else {
    JOptionPane.showMessageDialog(null, "Weight should be positive");
    }
    } catch (NumberFormatException nfe) {}
    return;
    }

    for(Node node : graph.getNodes()) {
    if(DrawUtils.isOverlapping(e, node.getCoord())){
    JOptionPane.showMessageDialog(null, "Overlapping Node can't be created");
    return;
    }
    }

    graph.addNode(e.getPoint());
    graph.setSolved(false);
    repaint();
    }

    //Mouse action press
    public void mousePressed(MouseEvent e) {

    }

    @Override
    public void mouseReleased(MouseEvent e) {
    for (Node node : graph.getNodes()) {
    if(selectedNode !=null && node!= selectedNode && DrawUtils.isWithinBounds(e, node.getCoord())){
    Edge new_edge = new Edge(selectedNode, node);
    graph.addEdge(new_edge);
    graph.setSolved(false);
    }
    }
    selectedNode = null;
    hoveredNode = null;
    repaint();
    }

    @Override
    public void mouseEntered(MouseEvent e) {

    }

    @Override
    public void mouseExited(MouseEvent e) {

    }

    //Mouse action drag
    public void mouseDragged(MouseEvent e) {
    hoveredNode = null;

    for (Node node : graph.getNodes()) {
    if(selectedNode ==null && DrawUtils.isWithinBounds(e, node.getCoord())){
    selectedNode = node;
    } else if(DrawUtils.isWithinBounds(e, node.getCoord())) {
    hoveredNode = node;
    }
    }

    if(selectedNode !=null){
    if(e.isControlDown()){
    selectedNode.setCoord(e.getX(), e.getY());
    cursor = null;
    repaint();
    return;
    }

    cursor = new Point(e.getX(), e.getY());
    repaint();
    }
    }

    //mouse moved action
    public void mouseMoved(MouseEvent e) {

    if(e.isControlDown()){
    hoveredNode = null;
    for (Node node : graph.getNodes()) {
    if(DrawUtils.isWithinBounds(e, node.getCoord())) {
    hoveredNode = node;
    }
    }
    }

    hoveredEdge = null;

    for (Edge edge : graph.getEdges()) {
    if(DrawUtils.isOnEdge(e, edge)) {
    hoveredEdge = edge;
    }
    }

    repaint();
    }

    //Reset
    public void reset(){
    graph.clear();
    selectedNode = null;
    hoveredNode = null;
    hoveredEdge = null;
    repaint();
    }
    }
    ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    MainWindow class

    package gui;

    import algo.DijkstraAlgorithm;
    import models.Graph;

    import javax.imageio.ImageIO;
    import javax.swing.*;
    import javax.swing.border.EmptyBorder;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.IOException;

    public class MainWindow extends JPanel
    {

    private Graph graph;
    private GraphPanel graphPanel;

    //Initialization of the Main Windows
    public MainWindow()
    {
    super.setLayout(new BorderLayout());
    setGraphPanel();
    }

    //Set graph panel
    private void setGraphPanel()
    {
    graph = new Graph();
    graphPanel = new GraphPanel(graph);
    graphPanel.setPreferredSize(new Dimension(9000, 4096));

    JScrollPane scroll = new JScrollPane();
    scroll.setViewportView(graphPanel);
    scroll.setPreferredSize(new Dimension(750, 500));
    scroll.getViewport().setViewPosition(new Point(4100, 0));
    add(scroll, BorderLayout.CENTER);
    setTopPanel();
    setButtons();
    }

    //Set top panel
    private void setTopPanel() {
    JLabel info = new JLabel("Algorithme de Routage");
    info.setForeground(new Color(230, 220, 250));
    JPanel panel = new JPanel();
    panel.setBackground(new Color(130, 50, 250));
    panel.add(info);
    panel.setBorder(new EmptyBorder(5, 5, 5, 5));
    add(panel, BorderLayout.NORTH);
    }

    //Set Buttons
    private void setButtons(){
    JButton run = new JButton();
    setupIcon(run, "run");
    JButton reset = new JButton();
    setupIcon(reset, "reset");
    final JButton info = new JButton();
    setupIcon(info, "info");

    JPanel buttonPanel = new JPanel();
    buttonPanel.setBackground(DrawUtils.parseColor("#D DDDDD"));
    buttonPanel.add(reset);
    buttonPanel.add(run);
    buttonPanel.add(info);

    reset.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
    graphPanel.reset();
    }
    });

    info.addActionListener(new ActionListener() {
    @Override
    //Mouse action
    public void actionPerformed(ActionEvent e) {
    JOptionPane.showMessageDialog(null,
    "Click on empty space to create new node\n" +
    "Drag from node to node to create an edge\n" +
    "Click on edges to set the weight\n\n" +
    "Combinations:\n" +
    "Shift + D Click : Set node as source\n" +
    "Shift + S Click : Set node as destination\n" +
    "Ctrl + Drag : Reposition Node\n" +
    "Ctrl + Click : Get Path of Node\n" +
    "Ctrl + Shift + Click : Delete Node/Edge\n");
    }
    });

    run.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
    DijkstraAlgorithm dijkstraAlgorithm = new DijkstraAlgorithm(graph);
    try{
    dijkstraAlgorithm.run();
    graphPanel.setPath(dijkstraAlgorithm.getDestinatio nPath());
    } catch (IllegalStateException ise){
    JOptionPane.showMessageDialog(null, ise.getMessage());
    }
    }
    });

    add(buttonPanel, BorderLayout.SOUTH);
    }

    //icon set
    private void setupIcon(JButton button, String img){
    try {
    Image icon = ImageIO.read(getClass().getResource(
    "/resources/" + img + ".png"));
    ImageIcon imageIcon = new ImageIcon(icon);
    button.setIcon(imageIcon);
    button.setBorderPainted(false);
    button.setFocusPainted(false);
    button.setContentAreaFilled(false);
    } catch (IOException e) {
    e.printStackTrace();
    }
    }

    }
    -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    Dijkstra Algorithm

    package algo;

    //Dijkstra Algorithm implemented
    import models.Edge;
    import models.Graph;
    import models.Node;

    import java.util.*;

    public class DijkstraAlgorithm
    {
    private boolean safe = false;
    private String message = null;

    private Graph graph;
    private Map<Node, Node> predecessors;
    private Map<Node, Integer> distances;

    private PriorityQueue<Node> unvisited;
    private HashSet<Node> visited;

    //get the distance between two nodes
    public class NodeComparator implements Comparator<Node>
    {

    public int compare(Node node1, Node node2)
    {
    return distances.get(node1) - distances.get(node2);
    }
    };

    //Dijkstra Algorithme
    public DijkstraAlgorithm(Graph graph)
    {
    this.graph = graph;
    predecessors = new HashMap<>();
    distances = new HashMap<>();

    for(Node node : graph.getNodes()){
    distances.put(node, Integer.MAX_VALUE);
    }
    visited = new HashSet<>();

    safe = evaluate();
    }

    //Evaluation if Source or Destination are present in the graph
    private boolean evaluate()
    {
    if(graph.getSource()==null)
    {
    message = "Source must be present in the graph";
    return false;
    }

    if(graph.getDestination()==null){
    message = "Destination must be present in the graph";
    return false;
    }

    for(Node node : graph.getNodes()){
    if(!graph.isNodeReachable(node)){
    message = "Graph contains unreachable nodes";
    return false;
    }
    }

    return true;
    }

    //
    public void run() throws IllegalStateException
    {
    if(!safe)
    {
    throw new IllegalStateException(message);
    }

    unvisited = new PriorityQueue<>(graph.getNodes().size(), new NodeComparator());

    Node source = graph.getSource();
    distances.put(source, 0);
    visited.add(source);

    for (Edge neighbor : getNeighbors(source)){
    Node adjacent = getAdjacent(neighbor, source);
    if(adjacent==null)
    continue;

    distances.put(adjacent, neighbor.getWeight());
    predecessors.put(adjacent, source);
    unvisited.add(adjacent);
    }

    while (!unvisited.isEmpty()){
    Node current = unvisited.poll();

    updateDistance(current);

    unvisited.remove(current);
    visited.add(current);
    }

    for(Node node : graph.getNodes()) {
    node.setPath(getPath(node));
    }

    graph.setSolved(true);

    }

    //update distance
    private void updateDistance(Node node)
    {
    int distance = distances.get(node);

    for (Edge neighbor : getNeighbors(node)){
    Node adjacent = getAdjacent(neighbor, node);
    if(visited.contains(adjacent))
    continue;

    int current_dist = distances.get(adjacent);
    int new_dist = distance + neighbor.getWeight();

    if(new_dist < current_dist) {
    distances.put(adjacent, new_dist);
    predecessors.put(adjacent, node);
    unvisited.add(adjacent);
    }
    }
    }

    //Get the adjacent Node
    private Node getAdjacent(Edge edge, Node node)
    {
    if(edge.getNodeOne()!=node && edge.getNodeTwo()!=node)
    return null;

    return node==edge.getNodeTwo()?edge.getNodeOne():edge.get NodeTwo();
    }

    //Get the Neighbors Nodes
    private List<Edge> getNeighbors(Node node)
    {
    List<Edge> neighbors = new ArrayList<>();

    for(Edge edge : graph.getEdges()){
    if(edge.getNodeOne()==node ||edge.getNodeTwo()==node)
    neighbors.add(edge);
    }

    return neighbors;
    }

    //Get the distance to the destination Node
    public Integer getDestinationDistance(){
    return distances.get(graph.getDestination());
    }

    // Get the distance between Node
    public Integer getDistance(Node node)
    {
    return distances.get(node);
    }

    //get the path between the Node to the destination Node
    public List<Node> getDestinationPath()
    {
    return getPath(graph.getDestination());
    }


    //Get the path between Nodes
    public List<Node> getPath(Node node){
    List<Node> path = new ArrayList<>();

    Node current = node;
    path.add(current);
    while (current!=graph.getSource()){
    current = predecessors.get(current);
    path.add(current);
    }

    Collections.reverse(path);

    return path;
    }

    }
    -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    the main

    import gui.MainWindow;

    import javax.swing.*;
    import java.awt.*;

    //main Class
    public class Main {

    public static void main(String[] args)
    {
    try
    {
    UIManager.setLookAndFeel(UIManager.getSystemLookAn dFeelClassName());
    } catch (Exception e) { }

    JFrame j = new JFrame();
    j.setTitle("Dijkstra Algorithm");

    j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    j.setSize(new Dimension(900, 600));
    j.add(new MainWindow());
    j.setVisible(true);

    }

    }

    --- Update ---

    I want realise it using JavaFX
    Change the classic node by laptop screen which will be added when we click to make them appear
    visualize some packet coming from the source node to the destination node

    --- Update ---

    I want realise it using JavaFX
    Change the classic node by laptop screen which will be added when we click to make them appear
    visualize some packet coming from the source node to the destination node

  10. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: help for Animated application

    Please edit your post and wrap your code with code tags:

    [code]
    **YOUR CODE GOES HERE**
    [/code]

    to get highlighting and preserve formatting.

    Have you added code to preload the path so that the changes you want to make can easily be tested?
    If you don't understand my answer, don't ignore it, ask a question.

  11. #11
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: help for Animated application

    Most of the comments are redundant and do not provide any help understanding what the code is doing.
    For example:
        private Point coord = new Point(); // An instance of Point
    coord is obviously an instance of Point. What is it used for? Why have a default value of 0,0?

        //Set node id
        public void setId(int id)
    The method's name says that.

        //Checking if two nodes are reachable
        public boolean isNodeReachable(Node node)
    Again the method name says that.
    BUT there are no comments saying what makes a node is reachable or how the code is going to determine that.

    This method has no comments to describe how it does its job:
        public static boolean isWithinBounds(MouseEvent e, Point p)

    And lots more than can be posted here.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. Issue while deploying JNLP application in Webspher Application Server.
    By nageshvk in forum What's Wrong With My Code?
    Replies: 1
    Last Post: March 11th, 2014, 09:12 AM
  2. Replies: 1
    Last Post: August 23rd, 2013, 06:33 AM
  3. two animated sprites collide
    By risen375 in forum AWT / Java Swing
    Replies: 1
    Last Post: June 22nd, 2011, 08:23 AM
  4. Replies: 0
    Last Post: December 3rd, 2009, 04:43 PM
  5. How to animate pictures using JCreator?
    By bil_Imma in forum AWT / Java Swing
    Replies: 6
    Last Post: February 13th, 2009, 07:00 AM