Search code examples
javaswinggraphicsawtsegment

Troubles using Java Graphics API


I'm new to AWT/Swing in Java and I'm triying just to draw two points and the asociated segment. The code I wrote is very simple:

   g.fillOval(100, 100, 10, 10);
   g.fillOval(200, 500, 10, 10);
   g.drawLine(100, 100, 200, 500);

But it doesn't work as I expected as you can see in the image below. I don't have reputation enought to post images so please check it on this Dropbox link .

enter image description here

Am I wrong when I say that the end of the segment should be inside the points? I don't know what I'm doing wrong :/ Thanks all.


Solution

  • Your problem is that the x and y points of the oval are the top-left corner of the rectangle that encloses it, and your lines are ending on these corners. Instead you should have your lines end in the centers of the ovals. The centers can be calculated easily by adding 1/2 the width and height of the ovals to the left-upper corners giving you something like:

    g.drawLine(105, 105, 205, 505);
    

    Note: avoid "magic" numbers where possible.

    e.g.,

    private int r = 5;
    private int x1 = 100;
    private int y1 = 100;
    private int x2 = 200;
    private int y2 = 500;
    
    
    // elsewhere in your paintComponent method:
    g.fillOval(x1, y1, 2 * r, 2 * r);
    g.fillOval(x2, y2, 2 * r, 2 * r);
    g.drawLine(x1 + r, y1 + r, x2 + r, y2 + r);