Search code examples
javagraphicspaintrepaint

Is there a way to make a section of the paint() method only run once in Java?


I am trying to make an Uno game (not important), so I need to draw some rectangles and images at the start of the game to set up. However, when the deck is clicked, it needs to add a card to the player's hand. This would obviously be at a different time than the original setup, but since it involves drawing a card, doesn't it also need to be within paint()? I tried to fix this by creating booleans and changing them depending on if the drawing has already been made, but when I did that it now does not draw the start drawing at all. Is there an easier way to do this or at least a solution to this issue? There is a lot more code, but I think what I have below is all that is needed for this issue. Thanks!

public class ImageCreator {

private boolean hasStartedDrawing = false;
private boolean drawCardPlayer = false;

public void mouseClicked(MouseEvent e)
{  
    if ((e.getX() >= 472 && e.getX() <= 662) && (e.getY() >= 205 && e.getY() <= 455))
    {
        drawCardPlayer = true;
        repaint();
    }
}

public void paintComponent(Graphics g)
{
    Graphics2D g2 = (Graphics2D) g;
    if (hasStartedDrawing == false)
    {
        Rectangle rect0P = new Rectangle(50, 650, 95, 125); g2.draw(rect0P); 
        hasStartedDrawing = true;
    {
    if (drawCardPlayer)
    {
        game.drawCardPlayer(g); //a method in another class that actually draws the card
        drawCardPlayer = false;
    }
}

}


Solution

  • You are doing it just great! Just a little detail, I struggle with it too in the beggining.

    The best aproach is to override paintComponent, and then call repaint every time what you need to update or "draw" the GUI again. If you need a more deep explanation, here you have the "why": https://www.oracle.com/java/technologies/painting.html

    And if you need some easy (but important) examples, here you have (also from Oracle Documentation): https://docs.oracle.com/javase/tutorial/uiswing/painting/index.html