1

I am practicing Java, trying to get back into OOP programming. I decided to recreate snake using a tutorial online. I am using Graphics for my code and i was wondering if the paintComponent() method is called 60 times a second or something similar. My probelm is that i am building some walls, if the snake collides he dies, the walls however i only want them drawn once, but it seems that the walls are drawn over and over again (I tested this using sysout). Some code is provided below:

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        draw(g);
    }

Inside the draw function

//Draw wall
wall1 = new Walls(10, 10, 10, 20, UNIT_SIZE, g);

The Walls constructor

Walls(int startX, int startY, int endX, int endY, int UNIT_SIZE, Graphics g)
    {
        this.startX = startX;
        this.startY = startY;
        this.endX = endX;
        this.endY = endY;
        g.setColor(Color.GRAY);
        for(int i = startY; i<=endY; i++)
        {
            for(int j = startX; j<=endX; j++)
            {
                g.fillRect(UNIT_SIZE*j, UNIT_SIZE*i, UNIT_SIZE, UNIT_SIZE);
            }
        }
    }
1
  • Swing animation works like a cartoon. You have to redraw the entire image for each frame of the animation. Commented Feb 9, 2021 at 14:16

1 Answer 1

1

The Swing painting system calls paintComponent() whenever there's a need to update something about the appearance of your component. The reason can be that the window was hidden or partially obscured and now becomes visible again, or that the contents of the component changed.

So, whenever Swing calls paintComponent(), it's important to draw everything that falls into the paint-requested part of the component, otherwise you'll get nasty paint artifacts like missing elements or leftovers from previous window states.

From your description, I guess it's mostly your software requesting a repaint of your component, by calling the repaint() method somewhere in your code. My recommendations:

  • Make sure you supply a rectangle to the repaint() call specifying the region that has changed (the snake head, more or less). Swing only repaints the component parts that are known to need it, by setting a fitted clipping region before calling paintComponent().
  • Optimize your paintComponent() implementation to check whether the clipping region of the Graphics object intersects with your walls. If not, you can skip painting the walls.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.