Bob
Bob

Reputation: 10775

Draw points as ovals using java swing

I have a point with [x, y] coordinate, for example Point p = new Point(1, 2). I want to visualize it. However, I want this point to an oval, like in the picture below.

enter image description here

How can I do that using java Swing?

Upvotes: 1

Views: 226

Answers (2)

Paul Samsotha
Paul Samsotha

Reputation: 208944

Determine the size of the oval you want, for example 10 px. Then draw the oval with the x and y points starting at the Point (x and y), minus half the size. Something like:

public class PointsPanel extends JPanel {
    List<Point> points = new ArrayList<Point>();
    int size = 10;
    ...
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        for (Point p : points) {
            int x = p.x - size/2;
            int y = p.y - size/2;
            g.drawOval(x, y, size, size);
        }
    }
}

For more general details on painting, see Performing Custom Painting. Also see the Graphics API for other drawXxx and fillXxx methods.

Upvotes: 4

Adisesha
Adisesha

Reputation: 5258

From the image you posted, what you need is a graph layout library like JUNG(not sure about current status of this project). You can follow peeskillet's answer but need to take care of problems like overlapping ovals etc.

Upvotes: 0

Related Questions