Go4Expert

Go4Expert (http://www.go4expert.com/)
-   Java (http://www.go4expert.com/articles/java-tutorials/)
-   -   Basic Graphics In Java With Examples (http://www.go4expert.com/articles/basic-graphics-java-examples-t21845/)

techgeek.in 20Apr2010 09:52

Basic Graphics In Java With Examples
 
Some Examples are same from Java AWT Reference and is because when I did those in my college days referred many sources.

Introduction



Graphics in any language gives a wonderful look and feel to the users as well as programmers. Programmers draw figures, strings etc with the help of graphics. Without graphics the windows programming is incomplete. Java is not behind. Java provides Abstract Window Toolkit.

AWT



The Abstract Window Toolkit (AWT) is Java's original platform-independent windowing, graphics, and user-interface widget toolkit. The AWT classes are contained in the java.awt package. It is one of Java’s largest packages. Because it is logically organized in a top-down, hierarchical fashion, it is easier to understand and use.

Some of the AWT classes are as follows:

AWTEvent ----------> Encapsulates AWT events.
Button ------------> Creates a push button control.
Checkbox ----------> Creates a check box control.
CheckboxGroup -----> Creates a group of check box controls.
CheckboxMenuItem --> Creates an on/off menu item.
Choice ------------> Creates a pop-up list.
Color -------------> Manages colors in a portable, platform-independent fashion.
Component ---------> An abstract superclass for various AWT components.
Container ---------> A subclass of Component that can hold other components
Event -------------> Encapsulates events.
Font --------------> Encapsulates a type font.
Graphics ----------> Encapsulates the graphics context. This context is used by the various output methods to display output in a window.
Image -------------> Encapsulates graphical images.
Label -------------> Creates a label that displays a string.
List --------------> Creates a list from which the user can choose
MediaTracker ------> Manages media objects.
Menu --------------> Creates a pull-down menu.
MenuBar -----------> Creates a menu bar.
Point -------------> Encapsulates a Cartesian coordinate pair, stored in x and y.
TextArea ----------> Creates a multiline edit control.
TextField ---------> Creates a single-line edit control
Window ------------> Creates a window with no frame, no menu bar, and no title.

The AWT defines windows according to a class hierarchy. The two most common windows are those derived from Panel, which is used by applets, and those derived from Frame, which creates a standard window.

Component
The Component class is at the top of the AWT hierarchy. It is an abstract class that encapsulates all of the attributes of a visual component. All user interface elements that are displayed on the screen and that interact with the user are subclasses of Component.

Container
The Container class is a subclass of Component class. It has additional methods that allow other Component objects to be nested within it. Other Container objects can be stored inside of a Container.

Panel
The Panel class is a concrete subclass of Container. It doesn’t add any new methods and implements Container. Panel is the superclass for Applet. When screen output is directed to an applet, it is drawn on the surface of a Panel object. A Panel is a window that does not contain a title bar, menu bar, or border.

Window
The Window class creates a top-level window. It is not contained within any other object. It sits directly on the desktop.

Frame
Frame encapsulates a “window.” It is a subclass of Window and has a title bar, menu bar, borders, and resizing corners.

Canvas
It is not considered as a part of the hierarchy for applet or frame windows. Canvas encapsulates a blank window upon which you can draw.

Graphics class



We will discuss about the Graphics class and its various methods in this article.

The Graphics class is an abstract class that provides the means to access different graphics devices. It lets us draw images on the screen, display images, and so forth. It is an abstract class because working with graphics requires detailed knowledge of the platform on which the program runs. The actual work is done by concrete classes that are closely tied to a particular platform. Your Java Virtual Machine vendor provides the necessary concrete classes for your environment. Once you have a Graphics object, you can call all the methods of the Graphics class without caring about platform specific classes. We rarely need to create a Graphics object yourself; its constructor is protected and is only called by the subclasses that extend Graphics. A Graphics object is always available when you override a component's paint() and update() methods. It is the sole parameter of the Component.paint() and Component.update() methods. We can also get a graphics context of a Component by calling Component.getGraphics().

The Graphics class defines a number of drawing functions. Each shape can be drawn edge-only or filled. Objects are drawn and filled in the currently selected graphics color, which is black by default. When a graphics object is drawn that exceeds the dimensions of the window, output is automatically clipped.

Drawing Strings



These methods let you draw text strings on the screen. The coordinates refer to the left end of the text's baseline.

public abstract void drawString (String text, int x, int y) :- This method draws text which is specified as the method’s argument on the screen in the current font and color, starting at position (x, y).

public void drawChars (char text[], int offset, int length, int x, int y):- The drawChars() method creates a String from the char array text starting at text[offset] and continuing for length characters. The newly created String is then drawn on the screen in the current font and color, starting at position (x, y). The starting coordinates specify the left end of the String's baseline.

public void drawBytes (byte text[], int offset, int length, int x, int y):- The drawBytes() method creates a String from the byte array text starting at text[offset] and continuing for length characters. This String is then drawn on the screen in the current font and color, starting at position (x, y). The starting coordinates specify the left end of the String's baseline.

Drawing Lines



public abstract void drawLine (int x1, int y1, int x2, int y2):- The drawLine() method draws a line on the graphics context in the current color that begins at startX,startY and ends at endX,endY. If (x1, y1) and (x2, y2) are the same point, it will draw a point. There is no method specific to drawing a point.

The following example illustrates the above method:
Code:

import java.awt.*;
import java.applet.*;
/*
<applet code="Rectangles" width=300 height=200>
</applet>
*/

public class Lines extends Applet
{
        public void init()
        {
                setBackground (Color.black);
                setForeground(Color.green);
        }

        public void paint(Graphics g)
        {
                g.drawLine(0, 0, 100, 100);
                g.drawLine(0, 100, 100, 0);
                g.drawLine(40, 25, 250, 180);
                g.drawLine(75, 90, 400, 400);
                g.drawLine(20, 150, 400, 40); //line
                g.drawLine(5, 290, 80, 19); //line
                g.drawLine (5, 75, 5, 75); // point
                g.drawLine (50, 5, 50, 5); // point
        }
}

Output:-
http://www.go4expert.com/images/arti...graphics/1.jpg

Drawing Rectangle



public void drawRect (int x, int y, int width, int height):- The drawRect() method draws a rectangle on the drawing area in the current color from (x, y) to (x+width, y+height). If width or height is negative, nothing is drawn.

public abstract void fillRect (int x, int y, int width, int height):- The fillRect() method draws a filled rectangle on the drawing area in the current color from (x, y) to (x+width-1, y+height-1). The filled rectangle is one pixel smaller to the right and bottom than requested. If width or height is negative, nothing is drawn.

public abstract void drawRoundRect (int x, int y, int width, int height, int arcWidth, int arcHeight):- The drawRoundRect() method draws a rectangle on the drawing area in the current color from (x, y) to (x+width, y+height). Instead of perpendicular corners, the corners are rounded with a horizontal diameter of arcWidth and a vertical diameter of arcHeight. If width or height is a negative number, nothing is drawn. If width, height, arcWidth, and arcHeight are all equal, you get a circle.

public abstract void fillRoundRect (int x, int y, int width, int height, int arcWidth, int arcHeight):-
The fillRoundRect() method is similar to drawRoundRect() method except that it draws a filled rectangle on the drawing area in the current color from (x, y) to (x+width-1, y+height-1). If width, height, arcWidth, and arcHeight are all equal, you get a filled circle.

The following example illustrates the above method:
Code:

import java.awt.*;
import java.applet.*;
/*
<applet code="Rectangles" width=300 height=200>
</applet>
*/
public class Rectangles extends Applet
{
        public void init()
        {
                setBackground(Color.black);
                setForeground(Color.green);
        }
         
        public void paint(Graphics g)
        {
                g.drawRect(10, 10, 60, 50);
                g.fillRect(100, 10, 60, 50);
                g.drawRoundRect(190, 10, 60, 50, 15, 15);
                g.fillRoundRect(70, 90, 140, 100, 30, 40);
        }
}

Output:-
http://www.go4expert.com/images/arti...graphics/2.jpg

public void draw3DRect (int x, int y, int width, int height, boolean raised):-
The draw3DRect() method draws a rectangle in the current color from (x, y) to (x+width,
y+height). A shadow effect makes the rectangle appear to float slightly above or below the screen. The raised parameter has an effect only if the current color is not black. If raised is true, the rectangle looks like a button waiting to be pushed. If raised is false, the rectangle looks like a depressed button. If width or height is negative, the shadow appears from another direction.

public void fill3DRect (int x, int y, int width, int height, boolean raised):-
It is similar to the draw3DRect ( ) method except that it draws a filled rectangle in the current color from (x, y) to (x+width,y+height).. If width or height is negative, the shadow appears from another direction, and the rectangle isn't filled.
Code:

import java.awt.*;
import java.applet.*;
/*
<applet code="Rectangles3D" width=300 height=200>
</applet>
*/
public class Rectangles3D extends Applet
{
        public void init()
        {
                setBackground(Color.black);       
        }         
        public void paint(Graphics g)
        {
                g.setColor (Color.gray);
                g.draw3DRect (25, 10, 50, 75, true);
                g.draw3DRect (25, 110, 50, 75, false);
                g.fill3DRect (100, 10, 50, 75, true);
                g.fill3DRect (100, 110, 50, 75, false);
        }
}

Output:-
http://www.go4expert.com/images/arti...graphics/3.jpg

Drawing Ellipses and Circles and Ovals



public abstract void drawOval (int x, int y, int width, int height):- The drawOval() method draws an oval in the current color within an invisible bounding rectangle from (x, y) to (x+width, y+height). You cannot specify the oval's center point and radii. If width and height are equal, you get a circle. If width or height is negative, nothing is drawn.

public abstract void fillOval (int x, int y, int width, int height):- The fillOval() method draws a filled oval in the current color within an invisible bounding rectangle from (x, y) to (x+width-1, y+height-1). You cannot specify the oval's center point and radii. Notice that the filled oval is one pixel smaller to the right and bottom than requested. If width or height is negative, nothing is drawn.

Code:

import java.awt.*;
import java.applet.*;
/*
<applet code="Ovals" width=300 height=200>
</applet>
*/
public class Ovals extends Applet
{
        public void init()
        {
                setBackground(Color.black);
                setForeground(Color.green);
        }

        public void paint(Graphics g)
        {
                g.drawOval(10, 10, 50, 50);
                g.fillOval(100, 10, 75, 50);
                g.drawOval(190, 10, 90, 30);
                g.fillOval(70, 90, 140, 100);
        }
}

Output:-
http://www.go4expert.com/images/arti...graphics/4.jpg

Drawing Arcs



public abstract void drawArc (int x, int y, int width, int height, int startAngle, int arcAngle):-
The drawArc() method draws an arc in the current color within an invisible bounding rectangle from (x,y) to (x+width, y+height). The arc starts at startAngle degrees and goes to startAngle + arcAngle degrees. An angle of 0 degrees is at the 3 o'clock position; angles increase counter-clockwise. If arcAngle is negative, drawing is in a clockwise direction. If width and height are equal and arcAngle is 360 degrees, drawArc() draws a circle. If width or height is negative, nothing is drawn.

public abstract void fillArc (int x, int y, int width, int height, int startAngle, int arcAngle):-
The fillArc() method is similar to the drawArc() method except that it draws a filled arc in the current color within an invisible bounding rectangle from (x, y) to (x+width-1, y+height-1. If width and height are equal and arcAngle is 360 degrees, fillArc() draws a filled circle.

Following is an example that illustrates the above methods:
Code:

import java.awt.*;
import java.applet.*;
/*
<applet code="Arcs" width=300 height=200>
</applet>
*/
public class Arcs extends Applet
{
        public void init()
        {
                setBackground(Color.black);
                setForeground(Color.green);
        }

        public void paint(Graphics g)
        {
                g.drawArc(10, 40, 70, 70, 0, 75);
                g.fillArc(100, 40, 70, 70, 0, 75) ;
                g.drawArc(10, 100, 70, 80, 0, 175);
                g.fillArc(100, 100, 70, 90, 0, 270);
                g.drawArc(200, 80, 80, 80, 0, 180);
        }
}

Output:-
http://www.go4expert.com/images/arti...graphics/5.jpg

Drawing Polygons



public abstract void drawPolygon (int xPoints[], int yPoints[], int numPoints):-
The drawPolygon() method draws a path of numPoints nodes by taking one element at a time out of xPoints and yPoints to make each point. The path is drawn in the current color. If either xPoints or yPoints does not have numPoints elements, drawPolygon() throws a run-time exception

public abstract void drawPolyline (int xPoints[], int yPoints[], int numPoints):- The drawPolyline() method functions like the 1.0 version of drawPolygon(). It connect the dots with the points in the xPoints and yPoints arrays and does not connect the endpoints. If either xPoints or yPoints does not have numPoints elements, drawPolygon() throws the run-time exception, ArrayIndexOutOfBoundsException.

public abstract void fillPolygon (int xPoints[], int yPoints[], int nPoints):- The fillPolygon() method draws a polygon of numPoints nodes by plucking one element at a time out of xPoints and yPoints to make each point. The polygon is drawn in the current color. If either xPoints or yPoints does not have numPoints elements, fillPolygon() throws the run-time exception IllegalArgumentException. If the polygon is not closed, fillPolygon() adds a segment connecting the endpoints.

Following is an example which illustrates the above methods:
Code:

import java.awt.*;
import java.applet.*;
/*
<applet code="HourGlass" width=230 height=210>
</applet>
*/
public class HourGlass extends Applet
{
        public void init()
        {
                setBackground(Color.black);
                setForeground(Color.green);
        }

        public void paint(Graphics g)
        {
                int xpoints[] = {30, 200, 30, 200, 30};
                int ypoints[] = {30, 30, 200, 200, 30};
                int num = 5;
                g.drawPolygon(xpoints, ypoints, num);
        }
}

Output:-
http://www.go4expert.com/images/arti...hics/5_001.jpg

Another Example:


Code:

import java.applet.*;
/*
<applet code="Polygons" width=230 height=210>
</applet>
*/
public class Polygons extends Applet
{
        public void init()
        {
                setBackground(Color.black);
                setForeground(Color.green);
        }

        public void paint(Graphics g)
        {
                int[] xPoints[] = {{50, 25, 25, 75, 75},
                                                {50, 25, 25, 75, 75},
                                                {100, 100, 150, 100, 150, 150, 125, 100, 150},
                                                {100, 100, 150, 100, 150, 150, 125, 100, 150}};
                int[] yPoints[] = {{10, 35, 85, 85, 35, 10},
                                                {110, 135, 185, 185, 135},
                                                {85, 35, 35, 85, 85, 35, 10, 35, 85},
                                                {185, 135, 135, 185, 185, 135, 110, 135, 185}};
                int nPoints[] = {5, 5, 9, 9};
                g.drawPolygon (xPoints[0], yPoints[0], nPoints[0]);
                g.fillPolygon (xPoints[1], yPoints[1], nPoints[1]);
                g.drawPolygon (new Polygon(xPoints[2], yPoints[2], nPoints[2]));
                g.fillPolygon (new Polygon(xPoints[3], yPoints[3], nPoints[3]));
        }
}

Output:-
http://www.go4expert.com/images/arti...graphics/6.jpg

shabbir 3May2010 13:15

Re: Basic Graphics In Java With Examples
 
Nominate this article for Article of the month - Apr 2010


All times are GMT +5.5. The time now is 10:15.