
Description: Display 3 red rectangles as indicated. Use 3 different rectangle objects, one for each rectangle. Dimensions of each rectangle: 40 x 40 pixels Starting position: The first rectangle�s top left hand coordinate must be at x = 50, y = 70

Java Swing Draw Rectangles
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.geom.*;
public class DrawRectangle extends JPanel {
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setPaint(Color.red);
int x = 40;
int y = 40;
Rectangle2D.Double rect1=new Rectangle2D.Double(x, y, 150, 100);
Rectangle2D.Double rect2=new Rectangle2D.Double(x, y, 200, 100);
Rectangle2D.Double rect3=new Rectangle2D.Double(x, y, 250, 100);
g2.draw(rect1);
g2.draw(rect2);
g2.draw(rect3);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setTitle("Show Different Polygons");
frame.setSize(350, 250);
Container contentPane = frame.getContentPane();
contentPane.add(new DrawRectangle());
frame.show();
}
}
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.