Draws points and labels with their coords - Java java.awt

Java examples for java.awt:Graphics2D

Description

Draws points and labels with their coords

Demo Code


import java.util.ArrayList;
import java.awt.Color;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.geom.*;

public class Main{
    public static final int scene_offset_x = 100;
    public static final int scene_offset_y = 500;
    public static final double point_diameter = 6.5;
    /**// w w w .j  a  v  a2  s .c o  m
     * Draws points and labels with their coords 
     */
    public static void drawPoints(Graphics2D g, ArrayList<Point> points,
            Color color, boolean labels) {
        FontMetrics fm = g.getFontMetrics();
        double point_radius = point_diameter / 2.0;
        g.setPaint(color);

        for (Point p : points) {
            Point2D.Double point = new Point2D.Double(p.getX(), p.getY());
            // Apply flip Y transform to point (not to text label)
            invertYAxisAffineTransform().transform(point, point);

            g.fill(new Ellipse2D.Double(point.getX() - point_radius, point
                    .getY() - point_radius, point_diameter, point_diameter));

            if (labels) {
                String text = p.toString();
                g.drawString(
                        text,
                        (float) (point.getX() - fm.stringWidth(text) / 2.0),
                        (float) (point.getY() - fm.getHeight()));
            }
        }
    }
    /**
     * Transform to flip Y axis and translate coords from
     * screen coords system to cartesian one
     */
    public static AffineTransform invertYAxisAffineTransform() {
        AffineTransform newAT = new AffineTransform();
        // Move center of coords by offset
        newAT.translate(scene_offset_x, scene_offset_y);
        // Flip Y axis
        newAT.scale(1.0, -1.0);
        return newAT;
    }
}

Related Tutorials