×

Java Programs

Java Practice

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.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	    window.setBounds(30, 30, 300, 300);
	    window.getContentPane().add(new MyCanvas());
	    window.setVisible(true);
	}
}

Output

draw a rectangle in java swing

Other recommended programs

Java Swing Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.