0
votes

I am working on a dependancy graph that consists of multiple nodes and multiple directed edges from one node to another in the graph.

I am trying to draw a visualation of the graph by adding n number of nodes as circles and edges between those nodes as a line.

I a using Graphics library of Java along with JPanel and Jframe.

This is currently the code I have made:

public class LoopUnrolling extends JPanel{


static int length = 5;
static String graph[][] = new String[length][length];


@Override
public void paintComponent(Graphics g){

    super.paintComponent(g);

    Random random = new Random();

    int x1 = random.nextInt(500);
    int y1 = random.nextInt(100);

    int x2 = random.nextInt(500);
    int y2 = random.nextInt(100);

    g.setColor(Color.red);
    g.drawOval(x1,y1,30,40);
    g.drawOval(x2,y2,30,40);
    g.drawLine(x1, y1, x2, y2);



}
public static void main(String[] args) {

         LoopUnrolling paintObject = new LoopUnrolling();
         JFrame jf = new JFrame();
         jf.setTitle("Dependancy Graph");
         jf.setSize(600,400);
         jf.setVisible(true);
         jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         jf.add(paintObject);
        }


 }

I was able to draw two circles and a line but the problem I am getting is connecting those two circles with an edge.

I have drawn each node at a random place on the canvas and want to add a Line between those two nodes. The line has Point1(x1,y1) and Point2(x2,y2). These points should be the points on two different Node's(Circles) outline

1
What is LoopUnrolling and what is you class extending? Please provide your full code and not just a small incorrect snippet.GAlexMES
LoopUnrolling is basically the name of the project.Muhammad Yasir Javed
No its a class you are using and adding to the JFrame. What is the purpose of that class?GAlexMES
Updated the code.Muhammad Yasir Javed
What exactly do you want to connect? The circle or the center of the ovales?GAlexMES

1 Answers

1
votes

You have two ellipses with centers

 cx1 = x1 + w1/2, cy1 = y1 + h1/2 
 and 
 cx2 = x2 + w2/2, cy2 = y2 + h2/2 

where wxx and hxx are width and height of ellipse (third and fourth parameters of drawOval)

Get difference vector

 dx = cx2 - cx1
 dy = cy2 - cy1

Normalize it

 len  = sqrt(dx*dx + dy*dy)
 dx = dx / len
 dy = dy / len

Now calculate points at circumference

 r1 = 0.5 * w1 * h1 / sqrt(w1*w1*dy*dy+h1*h1*dx*dx)
 px1 = cx1 + r1 * dx
 py1 = cy1 + r1 * dy

 r2 = 0.5 * w2 * h2 / sqrt(w2*w2*dy*dy+h2*h2*dx*dx)
 px2 = cx2 - r2 * dx
 py2 = cy2 - r2 * dy

And draw line segment (px1,py1)-(px2,py2)

Sample Delphi implementation and result: enter image description here