0

I have a drawShapeAt method in a class that should print a shape at a given location

@Override
    public void drawShapeAt(int x, int y) {
        try {
            canvas.removeMouseListener(ml);
        } catch (Exception e) {
        }

        polygon = new RegularPolygon(x, y, Integer.parseInt(polygonRadius), Integer.parseInt(polygonLines));
        BufferedImage image = new BufferedImage(800, 600, BufferedImage.TYPE_INT_ARGB);
        Graphics2D graphics = image.createGraphics();
        Random rand = new Random();
        graphics.setColor(new Color(rand.nextInt(0xFFFFFF)));
        graphics.fill(polygon);
        System.out.println("Painting polygon..");
        canvas.paintComponents(graphics);
    }
}

If I write for example canvas.setBackground it will change the background, yet it will not print the shape. My RegularPolygon is as follows:

public class RegularPolygon extends Polygon {
    public RegularPolygon(int x0, int y0, int radius, int sides) {
        double alpha = 2 * Math.PI / sides;
        for (int i = 0; i < sides; i++) {
            double x = x0 + radius * Math.cos(alpha * i);
            double y = y0 + radius * Math.sin(alpha * i);
            this.addPoint((int) x, (int) y);
        }
    }
}

I checked for wrong variables, but all are ok (x,y, polygonRadius, polygonLines).

Alexandru Antochi
  • 1,295
  • 3
  • 18
  • 42
  • Your code makes me very worried (why are you calling `paint`?), consider providing a runnable example which demonstrates your problem – MadProgrammer Apr 02 '17 at 23:45
  • Canvas is a JPanel. I need to paint `graphics` on it. – Alexandru Antochi Apr 02 '17 at 23:47
  • Not this way you don't. There should never be a need to call `paint` directly, that's not your responsibility. What's happening is, the panel is painting itself over the `Graphics` context you provided, wiping out what ever you painted to it previously - this is not how custom painting works – MadProgrammer Apr 02 '17 at 23:48
  • 1
    So you need to override the `paintComponent()` method of the panel. Read the section from the Swing tutorial on [Custom Painting](http://docs.oracle.com/javase/tutorial/uiswing/painting/step3.html) for more information and working examples. You can also check out [Custom Painting Approaches](https://tips4java.wordpress.com/2009/05/08/custom-painting-approaches/) for ways to paint multiple shapes on a panel. – camickr Apr 02 '17 at 23:48
  • For better help sooner, post a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). – Andrew Thompson Apr 03 '17 at 00:25

0 Answers0