Hello Guys,

I know how to draw line and shapes but how can i draw a parabol??? ( i need a 2D line)

Any suggestion or pointers are appreciated!

Dani AI

Generated

As asked, there are two practical ways to draw a parabola in Java: use Bezier primitives (single curve segments) or plot the formula point-by-point into a Path. 's CubicCurve2D hint is useful when a single Bezier arc is sufficient; 's Path2D approach is the simplest when an explicit formula y = ax^2 + bx + c is available and exact plotting is desired.

A straightforward, reliable method is sampling: pick an x range and resolution, compute y for each x, build a Path2D (moveTo first point, lineTo subsequent points), then draw that path with Graphics2D. Use an AffineTransform (translate + scale(1,-1)) to make +Y go up and enable antialiasing for a smooth result. Example:

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    double a = 0.01, b = 0, c = 0;
    int xMin = -200, xMax = 200;
    Path2D.Double path = new Path2D.Double();
    path.moveTo(xMin, a*xMin*xMin + b*xMin + c);
    for (int x = xMin + 1; x <= xMax; x++) {
        path.lineTo(x, a*x*x + b*x + c);
    }

    AffineTransform old = g2.getTransform();
    AffineTransform at = new AffineTransform();
    at.translate(getWidth()/2.0, getHeight()/2.0);
    at.scale(1, -1);
    g2.setTransform(at);
    g2.draw(path);
    g2.setTransform(old);
}

Notes and tips: increase the sampling density for smoother curves; use adaptive subdivision (split where curvature is high) to reduce point count; QuadCurve2D/CubicCurve2D can approximate or represent parabolic arcs with fewer segments when parametric control points are available. Pay attention to coordinate transforms (screen Y is down by default) and restore the Graphics2D transform after drawing. See the Path2D and QuadCurve2D API documentation for details on construction and control points (Path2D, QuadCurve2D).

Recommended Answers

All 2 Replies

Check out java.awt.geom in the Java API.
The CubicCurve2D may work for you.

You can could also create a Path2D instance and add points to it if you have a specific formula that you need to plot.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.