Search code examples
javaswinggraphicsawtpaintcomponent

How to use paintComponent() without calling multiple "draw()" methods?


I'm new to java and I'm trying to create a "game".

In my game I have the paintComponent method within my main class:

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    setBackground(new Color(120,120,255));
    BackgroundObject.drawGrass(g,385);
    BackgroundObject.drawRoad(g,420);
    BackgroundObject.drawSun(g,-20,-20);
    myCar.draw(g);
    debugger.draw(g);
}

The problem is that every object I want to draw, I have to put it under the paintComponent method (like when I wanted to draw the car, I have to put myCar.draw() under paintComponent)

Is there any way do this?

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    setBackground(new Color(120,120,255));
    visualComponents.draw(g);
    GUI.draw(g);
}

where any class can tell the visualComponent class to draw an object when visualComponents.draw() is called.

Ex: My car class tells visualComponent to draw the vehicle whenever visualComponent.draw(g); is called.

To sum it up I am basically asking for the structure of how most people use paintComponent for their programs

I have been looking around google but couldn't find the answer.

If my question confuses you let me know.


Solution

  • You might add the elements to a collection, then iterate the collection and draw each one in a loop. That could paint 100s of objects within a few lines of code.

    This example iterates a collection of Area instances & draws them using:

        for (Area obstacle : obstacles) {
            if (doAreasCollide(obstacle, player)) {
                g.setColor(Color.RED);
            } else {
                g.setColor(Color.GREEN);
            }
            g.fill(obstacle);
        }
    

    The 3 green & one red obstacles are in the collection, while the ball (small yellow circle) is drawn separately.