Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Hello, How can I alter the paint method so that the Java canvas GUI renders a bu

ID: 3773247 • Letter: H

Question

Hello,

How can I alter the paint method so that the Java canvas GUI renders a bunch of rectangles and then wipes them out and starts drawing them again multiple times. I dont want any other possible graphics to get wiped in this process, just the rectangles which keep repeating in a cycle. As of now the program pretty much does this but stops after one or two cycles. Is it possible that it is a bug on my machine?

This is the [CODE]

import java.awt.*;
import java.util.concurrent.TimeUnit;
import javax.swing.*;

public class RandomGeneratedRectangles
{
public static void main(String[] args)
{

// create a MyCanvas object
MyCanvas canvas1 = new MyCanvas();

// set up a JFrame to hold the canvas
JFrame frame = new JFrame();
frame.setTitle("Random rectangles");
frame.setSize(500, 500);
frame.setLocation(100, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// add the canvas to the frame as a content panel
frame.getContentPane().add(canvas1);
frame.setVisible(true);
} // end main()

} // end class

class MyCanvas extends Canvas
{

public MyCanvas()
{ } // end MyCanvas() constructor

public void paint(Graphics graphics)
{
  
int r; // red Color factor
int g; // green Color factor
int b; // blue Color factor

int x; // x coordinate to locate rectangle
int y; // y coordinate to locate rectangle
  
int width; // width of rectangle
int height; // height of rectangle
int i; // loop counter
  
// paint the canvas black
graphics.setColor(Color.BLACK);
graphics.fillRect(0, 0, 500, 500);
  
for(i=1; i<=100; i++)
{
// randomly generate and set a color
r = (int) (Math.random() * 256);
g = (int) (Math.random() * 256);
b = (int) (Math.random() * 256);
graphics.setColor(new Color(r, g, b));

// randomly generate and draw a rectangle
x = (int) (Math.random() * 500);
y = (int) (Math.random() * 500);
width = (int) (Math.random() * 250);
height = (int) (Math.random() * 250);
graphics.drawRoundRect(x, y, width, height, 20, 20);

// The sleep command delays the drawing to make it more interesting
  
try
{
TimeUnit.MILLISECONDS.sleep(20);
}
catch (Exception e)
{
System.out.println("Exception caught");
}

}
    }
}

Explanation / Answer

I went through your code and it looks perfectly fine. You may try to increase the sleep time to something more like 60 milliseconds or above. It might happen that since the time is too less so the implicit threads gets overlapped and does not execute properly.

TimeUnit.MILLISECONDS.sleep(90);

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote