Credits

Friday, March 25, 2011

More of Java's Graphics Samples

Graphics class  as previously noted is used to set  text or background colors, draw text and / or geometric shapes.


With the Graphics methods, we can draw different shapes of our own liking. The program below illustrates the use of fillPolygon to draw an octagon STOP sign and circles for PARKING sign.


Furthermore, Graphics class allows us to copy any section to another destination using copyArea ( ) method. This method can be written as,

g.copyArea(200,400,101,51,400,0);


The first two constants are the starting point for selection, and the next two constants shall be the width and height of selection while the last two constants shall be the starting point where selection shall be copied to. The program illustrates the use of copyArea and other  polygon methods.

[+/-] show/hide


import java.applet.*;
import java.awt.*;


public class GraphicsPolygons extends Applet {
int xPoints[]={200,100,100,200,300,400,400,300};
int yPoints[]={100,200,300,400,400,300,200,100};
int size=xPoints.length;

int xArr[]={700,800,700,700};
int yArr[]={100,150,200,100};
int Zsize=xArr.length;


Font newFont = new Font("Tahoma", Font.BOLD, 50);
Font otherFont = new Font("Tahoma", Font.BOLD, 100);
Color newColor=new Color(.80F,1F,.50F);

public void init()
{
setBackground(Color.gray);

}

public void paint(Graphics g)
{

//draws a stop sign
g.setColor(newColor);
g.fillPolygon(xPoints,yPoints,xPoints.length); //to fill a solid polygon
g.setColor(Color.black);
g.fillRect(200,400,100,50);
g.setFont(newFont);
g.drawString("STOP", 200, 250);

//draws a parking sign

g.setColor(Color.red);
g.fillRoundRect(550,200,200,200,200,200);
g.setColor(Color.gray);
g.fillRoundRect(570,225,150,150,150,150);
g.copyArea(200,400,101,51,400,0);
g.setFont(otherFont);
g.setColor(Color.black);
g.drawString("P", 630, 320);


}}

AddThis