I have a rectangle "ball" that is striking another rectangle "b1". I'm trying to make b1 the color of the background and not able to be hit by the ball object anymore, but I don't know how to do that and I couldn't find anything online. Any help is greatly appreciated! Below is the code I'm trying to write:

public void paintComponent(Graphics gc)

        setOpaque(false);
        super.paintComponent(gc);

        gc.setColor(Color.RED); //gc is the graphics component name
        Rectangle ball = new Rectangle(ballX, ballY, 7, 7);
        gc.fillRect((int) ball.getX(), (int) ball.getY(), (int) ball.getWidth(), (int) ball.getHeight());

        Rectangle b1 = new Rectangle(10,10,62,10);
        gc.fillRect((int) b1.getX(), (int) b1.getY(), (int) b1.getWidth(), (int) b1.getHeight());
}


public void run() 
{

        while(true)
        {

            if(game) //if the ball hits the bottom of the panel, the game is ended
            {

                if(ball.intersects(b1))
                {
                    /* code to make the rectangle b1 disappear 
                    and not able to be hit again */

                }
            }
        }
}

It's a bit of a cludge, but why not move b1 to some place way out of the picture?

  • enless loop by default causes flickering,

  • use Swing Timer with repaint instead of Runnable#Thread

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.