Home » Java programs » Java swing/awt programs

Java program to draw a rectangle using swing

In this java program, we are going to draw a rectangle using swing and awt.
Submitted by IncludeHelp, on November 25, 2017

In the following program, we use two classes java.swing and java.awt to draw a rectangle using these classes we can draw different shapes we want. For the rectangle we have to mention the co-ordinates to draw rectangle these co-ordinates are taken as an input of the point, these points will spread according to given co-ordinates and makes a rectangle.

Program to draw a rectangle in java

import java.awt.Graphics;
import javax.swing.JComponent;
import javax.swing.JFrame;

class MyCanvas extends JComponent 
	public void paint(Graphics g) 
	    g.drawRect (10, 10, 200, 200);  

public class DrawRectangle 
	public static void main(String[] a) 
	    JFrame window = new JFrame();
	    window.setBounds(30, 30, 300, 300);
	    window.getContentPane().add(new MyCanvas());


draw a rectangle in java swing

Other recommended programs

Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.

Comments and Discussions

We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.