Drawing Shapes in JAVA

Introduction

To make the interface more interactive and user engaging, developers often resort to adding shapes. In JAVA, shapes can be drawn using pre-defined methods of the Graphics class. Starting from rectangles to polygons, a variety of shapes can be drawn. A few simple imports have to be made to access the Graphics class and subclasses like DebugGraphics and Graphics2D. Some of the methods to draw various shapes are mentioned below:

  • void draw3DRect (int x, int y, int width, int height, boolean raised) – This method will outline a cube.
  • abstract void drawArc (int x, int y, int width, int height, int startAngle, int arcAngle) – Given the parameters, this method will draw part of a circle.
  • abstract void drawLine (int x1, int y1, int x2, int y2) – To draw a line starting and ending at the two given points.
  • abstract void drawOval (int x, int y, int width, int height) – This will draw an oval with the given specifications.
  • abstract void drawPolygon (int [] xPoints, int[] yPoints, int nPoints) – This method will draw a closed polygon based on the x and y matrices (arrays).

Examples

Let us now put to code some of the above methods in JAVA such that we get shapes as output to our code.

import java.awt.Component;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Polygon;
public class DemoShapes
{
public static void main(String[] args)
{
Frame frame = new Frame();
frame.add(new CustomPaintComponent());
int frameWidth = 300;
int frameHeight = 300;
frame.setSize(frameWidth, frameHeight);
frame.setVisible(true);
static class CustomPaintComponents extends Component {
//let us make a new Graphics2D object
Graphics2D g2d = (Graphics2D)g;
//Let us set a few common parameters for all the shapes we will deal with
int x = 0,
int y = 0;
int w = getSize().width-1;
int h = getSize().height-1;
//We will start with a line
g2d.drawLine(x, y, w, h);
//Oval
g2d.drawOval (x, y, w, h);
//Rectangle
g2d.drawRect(x, y, w, h);
//Arc of a circle
int startAngle = 45;
int arcAngle = -60;
g2d.drawArc(x, y, w/2, h/2, startAngle, arcAngle)
}
}
}

 

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.