Java programming basics
Learn Java from scratch with this easy notes... By Sandhya Chatarji
9 Graphics
AWT package provided in Java
allows drawing graphics. Graphic classes
provided in AWT package has a rich collection of methods. These methods are used to draw any graphical
figure like:-
Ø
Oval
Ø
Rectangle
Ø
Square
Ø
Circle
Ø
Lines
Ø
Text using different fonts.
While drawing these figures, we
can use different colors; we can paint the figures and so on. Frame, applet and canvas are possible medium
for graphics rendering. To draw any
figure, a graphic background is required.
Graphic background can be obtained by getGraphic ( ) method or when any
of the following three methods are called.
Ø
repaint(
): it is called anytime when there is
need to repaint the drawing object.
Ø
update(Graphic
g): it is called automatically by
the repaint ( ) method. update method
clears the drawing object and calls paint ( ) method by passing it to an object
of Graphics.
Ø
paint(Graphics
g): it is called by update( )
method. the graphics context passed to
this method is used for drawing. paint (
) method actually draws different graphical figures.
Drawing Strings, characters and bytes
To draw or print string on to
frame, drawstring ( ) method is provided in the Graphics class. This method accepts 3 parameters. They are:-
- The String to be drawn.
- x co-ordinate on the frame where string to be drawn.
- y co-ordinate on the frame where string to be drawn.
To draw or print characters on
the frame, drawChars ( ) method is provided in the Graphics class. This method accepts 5 parameters. They are:-
- character array
- offset position or starting position from where
characters are to be drawn.
- no of characters to be drawn from array.
- x co-ordinate, where drawing to be started.
- y co-ordinate, where drawing to be started.
To draw or print characters on
the frame, drawBytes( ) method is provided in the Graphics class. This method accepts 5 parameters. They are:-
- byte array
- offset position or starting position from where bytes
are to be drawn.
- no bytes to be drawn from array.
- x co-ordinate, where drawing to be started.
- y co-ordinate, where drawing to be started.
Example 1 (Drawings Characters,
Strings and Bytes)
import java.awt.*;
public class DrawString1 extends
Frame
{
public DrawString1( )
{
super("Draw Strings,
Characters,Bytes,Figures");
setSize(300,300);
setVisible(true);
}
public void paint(Graphics g)
{
g.setColor(Color.red);
g.drawString("Good
Morning",50,150);
g.drawString("Good
Afternoon",50,170);
g.drawString("Good
Night",50,190);
char ch[ ] =
{'a','b','c','d','e','f'};
g.drawChars(ch,2,4,100,125);
byte b[ ]
={100,101,102,103,104,105,106,107};
g.drawBytes(b,1,6,50,125);
}
public static void main(String
args[])
{
new DrawString1( );
}
}
Drawing Lines and Ovals
To draw a lines we have the
method called drawLine( ) it accepts 4 parameters. They are:-
- x-coordinate, where drawing to be started(x1).
- y-coordinate, where drawing to be started(y1).
- x-coordinate, where drawing to be completed(x2).
- y-coordinate, where drawing to be completed(y2).
We can draw the colorful lines by
setting required color. The setColor( )
method is provided to set color for graphical figures.
To draw the oval drawOVal ( )
method is provided. It accepts four
parameters. They are:-
- x-coordinate, where drawing to be started.
- y-coordinate, where drawing to be started.
- Width of the oval.
- Height of the oval.
Example2 (Drawings Lines and
Ovals)
import java.awt.*;
public class DrawFigure extends
Frame
{
public DrawFigure( )
{
super("Lines and
Ovals");
setSize(300,300);
setVisible(true);
}
public void paint(Graphics g)
{
g.setColor(Color.blue);
g.drawLine(75,75,125,75);
g.drawLine(100,50,100,100);
g.drawLine(112,55,112,95);
g.drawOval(100,150,70,40);
g.setColor(Color.cyan);
g.fillOval(200,150,50,100);
}
public static void main(String
args[])
{
new DrawFigure( );
}
}
Drawing Rectangles and Rounded Rectangles
The drawRect( )method is used to
draw a simple rectangle. This method
accepts four parameters. They are:
- x-coordinate
- y-coordinate
- width of the rectangle
- height of the rectangle.
The method drawRoundRect ( ) is
provided to draw the rounded rectangles.
This method takes six parameters, where first four parameters are same
as drawRect( ) method the additional two parameters are:-
- arcwidth of the rectangle
- archeight of the rectangle.
Example3 (Drawings Rectangles and
Rounded Rectangles )
import java.awt.*;
public class DrawRect extends
Frame
{
public DrawRect( )
{
super("Rectanlges");
setSize(500,500);
setVisible(true);
}
public void paint(Graphics g){
g.setColor(Color.green);
g.drawRect(50,50,60,60);
g.drawRoundRect(150,50,50,50,20,40);
g.setColor(Color.red);
g.fillRect(250,140,60,60);
g.fillRoundRect(150,140,50,50,20,20);
}
public static void main(String
args[])
{
new DrawRect( );
}
}
Drawing 3D rectangles and arcs
With draw3Drect( ) method we can
draw 3D rectangle. It accepts five
parameters. Where first four parameters
are same as drawRect( ) method, but value of the fifth parameter decides
whether rectangle to be drawn should be 3D or not. The fifth parameters is of type Boolean, true
value indicates rectangle should be 3D figure and false value indicates that it
should not be a 3D figure.
The drawArc( ) method is used to
draw arcs and fills it. The drawArc( )
method accepts six parameters. They
are:-
- x-coordinate, where drawing to be started.
- y-coordinate, where drawing to be started.
- Width of the arc.
- Height of the arc.
- Beginning of an angle.
- Angular extent of the arc, relative to the beginning
of an angle.
Drawing Polylines
The drawPolyline( ) method is
used to draw Poly lines. It accepts
three parameters. as:
- array storing x-coordinate of the points
- array storing y-coordinate of the points
- total number of points to draw line.
Drawing and Filling Polygons
There are two methods provided in
the Graphics class to draw polygons.
First method accepts object of polygon class and another method takes
two arrays of points and total number of points. The method drawPolygon accepts three
parameters like the drawpolyline( ) method.
They are :-
- array storing x-coordinate of the points
- array storing y-coordinate of the points
- total number of points to draw line.
Color control
Color control in Java is achieved
through three primary colors- Red, Green and Blue. These are primary colors of light. Java uses RGB color model. Object of color contains three integer or
float values for three parameters. i.e. Red, Green, Blue and in range from
0-255. Using these values we can also
create our own custom colors. Following
table shows RGB values of common colors.
Color
|
Red
|
Green
|
Blue
|
White
|
255
|
255
|
255
|
Light Grey
|
192
|
192
|
192
|
Gray
|
128
|
128
|
128
|
Dark Gray
|
64
|
64
|
64
|
Black
|
0
|
0
|
0
|
Pink
|
255
|
175
|
175
|
255
|
200
|
0
|
|
Yellow
|
255
|
255
|
0
|
Magenta
|
255
|
0
|
255
|
With these color values we can
create color object and set that color to draw or fill any graphical figure.
For example to create pink color the syntax is:
color
c = new color(255, 175, 175);
Creation of custom color is not
so easy. To create a color according to your wish, we have to try many combinations
of RGB values. Hence color class has
provided some predefined colors. These
color constants are used with classname prefixed to it. they:-
color.white color.black color.orange color.gray
color.lightgray color.darkgray color.red color.green
color.blue color.pink color.cyan color.magenta
color.yellow
Font Control
Fonts are used to display the
text in different form. Fonts are
supported by the system. The font class
provided in the Java.awt package allows us to use various fonts to display
text. This class includes several
methods. The method getAllFont( )
returns all font supported by the system and getFontList( ) returns font names
in string form which are present in the toolkit. Toolkit class is provided by the language,
which gives a platform dependent information like fonts available, screen size
etc.
Class FontMetrics
This class is provided to measure
various characters present in different fonts.
Measurement includes height, baseline, ascent and descent leading of a
font. This is essential, as all the
characters do not occupy same space when printed, in case of characters of the
same font as well as different fonts. So
the space required to print those characters need to be found out to avoid
overlapping or overwriting of characters.
Thus:-
Ø
Height refers to the size of tallest character
of the font.
Ø
Ascent refers to the distance from baseline to
the top of the characters.
Ø
Descent refers to the distance from baseline to
the bottom of the characters.
Ø
Leading refers to the extra forward spaces
required to position the next character.
Paint Mode
Objects are drawn using the paint
mode set. Wherever a new object is
drawn, it overwrites the original contents of the drawing object. Similarly, when objects are drawn repeatedly,
it erases previous contents of the drawing object and only new contents are
visible. To make old as well as new
contents visible on the screen, a method setXORMode(Color c ) is provided in
the Graphics class.
Practical Examples
Example 1( Drawing 3D Rectangles
and Arcs)
import java.awt.*;
public class DrawRectArc extends
Frame
{
public DrawRectArc( )
{
super("Arc and
Rectangles");
setSize(300,300);
setVisible(true);
}
public void paint(Graphics g)
{
g.setColor(Color.red);
g.draw3DRect(100,230,60,30,true);
g.drawArc(200,200,100,70,30,80);
g.fillArc(210,250,260,70,30,80);
}
public static void main(String
args[])
{
new DrawRectArc( );
}
}
Example2( Drawing Poly Lines)
import java.awt.*;
public class PolyLines extends
Frame
{
int x1[]={50,65,95,115,135};
int y1[]={50,60,60,75,60};
int x2[]={67,82,95,120,135};
int y2[]={150,130,160,155,180};
public PolyLines( ){
super("Poly Lines");
setSize(300,300);
setVisible(true);
}
public void paint(Graphics g)
{
g.drawPolyline(x1,y1,5);
g.setFont(new Font("Times
New Roman",Font.BOLD,15));
g.drawString("Poly Lines
Drawing",50,180);
g.setColor(Color.red);
g.drawPolyline(x2,y2,5);
}
public static void main(String
args[] ){
new PolyLines( );
}
}
Example3( Drawing Polgons)
import java.awt.*;
public class PolyFig extends
Frame
{
int x1[]={50,25,40,100,80};
int y1[]={50,70,120,120,80};
int x2[]={80,30,50,150,100,170};
int
y2[]={150,170,200,220,240,190};
public PolyFig( )
{
super("Poly Figures");
setSize(300,300);
setVisible(true);
}
public void paint(Graphics g)
{
g.drawPolygon(x1,y1,5);
g.setColor(Color.green);
g.fillPolygon(x2,y2,6);
}
public static void main(String
args[])
{
new PolyFig( );
}
}
Example4( Color Control)
import java.awt.*;
public class ColorControl extends
Frame
{
public ColorControl( )
{
super("Color Control");
setSize(300,300);
setVisible(true);
}
public void paint(Graphics g)
{
Color C1 = new Color
(230,140,60);
Color C2 = new Color(30,170,150);
Color C3 = new Color(120,60,200);
Color C4 = new Color(90,210,130);
g.setColor(C1);
int red =C1.getRed( );
int green =C1.getGreen( );
int blue =C1.getBlue( );
g.drawString("Sandhyashree
Sports Group",50,70);
String str="red :-"
+String.valueOf(red);
str += ", green :-"
+String.valueOf(green);
str += ", blue :-" +String.valueOf(blue);
g.drawString(str,50,100);
C1=C1.darker( );
g.setColor(C1);
g.drawString("Sandhyashree
Sports Group",50,125);
g.setColor(C2);
g.drawString("Sandhyashree
Sports Group",50,150);
C2=C2.brighter( );
g.setColor(C2);
g.drawString("Sandhyashree
Sports Group",50,175);
g.setColor(C3);
g.drawString("Sandhyashree
Sports Group",50,200);
g.setColor(C4);
g.drawString("Sandhyashree
Sports Group",50,225);
}
public static void main(String
args[])
{
new ColorControl( );
}
}
Example5(Using Font)
import java.awt.*;
class FontUse extends Frame
{
public FontUse( )
{
super("Different
Fonts");
setSize(400,300);
setVisible(true);
}
public void paint(Graphics g)
{
Font f=g.getFont( );
g.drawString("Default Font
is ",30,50);
g.drawString(String.valueOf(f),50,75);
Font f1 = new
Font("DialogInput",Font.BOLD,14);
g.setFont(f1);
g.drawString("Leena's
Software ",30,125);
Font f2 = new
Font("SansSerif",Font.ITALIC,16);
g.setFont(f2);
g.drawString("Leena's
Software ",30,150);
Font f3 = new
Font("Monospaced",Font.ITALIC+Font.BOLD,20);
g.setFont(f3);
g.drawString("Leena's Software
",30,200);
}
public static void main(String
args[]){
new FontUse( );
}
}
Example6(Moving Rectangle)
import java.awt.*;
import java.applet.*;
public class RectMover extends
Applet
{
public void paint(Graphics g)
{
int x=20;
for( ; x<240;x++)
{
g.setColor(Color.white);
g.drawRect(x-1,x-1,60-x,40-x);
g.setColor(Color.red);
g.drawRect(x,x,60+x,40+x);
for(int u=0;u<10000000;u++);
}
}
}
RectMover.html
<HTML>
<HEAD>
<TITLE>Moving
Rectanlge</TITLE>
</HEAD>
<BODY>
<APPLET CODE =
"RectMover.class" WIDTH = 400 HEIGHT =550>
</APPLET
</BODY>
</HTML>
8 Exception Handling
Whenever an Error is encountered
while executing a program, an Exception is said to have occurred. An exception can also be termed as a special
type of error. It arises at run time in
a code sequence, mostly, due to abnormal conditions that occur at the time of
running the program.
When an exception occurs, an
object, which represents that exception is created and passed to the method
where the exception has occurred. This
object contains delailed information about the exceptin, which can be retrieved
and processed. Exceptions can be thrown
by run-time environment such as IllegalAccessException or EmptyStackException
or it can be manually generated by the code.
Throwable class provided in the language is the super class of Exception
Class, which in turn is a super class of the individual exceptions.
Error and Exception handling is
used to foresee and identify error conditions and perform processing to take
care of their impact.
Exceptions in Java
Java provides an exception
handling model that allows us to check for errors where it is relevant to do
so. It implements a catch and throw
model of exception handling similar to the one used in C++. Instead of returning erros from a method
using the normal return value or parameter mechanism, java provides en
exception handling facility.
Errors and other exceptional
conditions are treated as distinct from the normal flow of control in the
program, which after all, they are. When
an error occurs, an exception is thrown.
Exceptions climb the chain of calls until they are caught or until the
program exists. The catch and throw
method of exception handling offers two big advantages:
1)
An error condition can be dealt with only where it
makes sense instead of dealing with it at every level between where it occurs
and where it needs to be dealt with.
2)
Code can be written as if the error message for a
particular error, whch we expect to occur, works, when the particular error is
caught.
Try and catch
The language support for the
catch and throw method of exception handling is the try / catch block. Following is the Try Block:-
try {
doFileProcessing( );
displayResults( ) ;
}
catch(Exception e){
System.err.println(“Error : “+
e.getMessage( ));
}
Any error that occurred during
the execution of doFileProcessing( ) or displayResults( ) would be caught by
catch( ) and processed as specified. If
an error occurred duging doFileProcessing( ), the method displayResults( )
would never get called, and the execution would proceed directly to the catch
block.
We can also usemultiple catch( )
blocks together and process various exception types differently.
try {
doFileProcessing( );
displayResults( ) ;
}
catch(LookException e){
handleLookExceptio (e);
}
catch(Exception e){
System.err.println(“Error : “+
e.getMessage( ));
}
in the above case, a
LookException would be caught and processed by the first catch and any other
type of exception would be handled by the second catch.
The finally Statement
Exceptions can cause control to
leave the current method without completing the method’s execution. If there is a cleanup code such as the code
required to close files at the end of the method, it will never get
called. To deal with this, java provides
finally block. The Finally block can be use in conjunction with a try
block. Basically it ensures that if an
exception has occurred, any cleanup work, which is necessary, is taken care of.
This is because the code in a finally block is guaranteed to run whether
an exception occurs or not. For
example:-
try {
doSomething( );
}
finally
{
CleanUp( ) ;
}
if the doSomeThing( ) throws an
exception, the cleanup ( ) method will still be called and then the exception
will continue to call other chain. If an
exception is not thrown, the CleanUp( ) is called and the execution will
proceed after the finally block.
Different types of Exceptions our
code can throw are as follows:-
Ø
Runtime Exception
o
ArithmethicException
o
IllegalArgumentException
o
ArrayIndexOutOfBoundsException
o
NullPointerException
o
SecurityException
o
NoSuchElementException
Ø
ClassNotFoundException
Ø
AWTException
Ø
DataFormatException
Ø
SQLException
Ø
IOException
o
UnKnownHostException
o
SocketException
o
EOFException
o
MalformedURLExeption
o
FileNotFoundException
Ø
IllegalAccessException
Ø
NoSuchMethodException
Purpose of Exception Handling
Whenever an exception occurs, in
the program in which proper exception handling mechanism is not provided, the
program aborts, leaving all the resources previously allocated in the same
state. This can lead to resource leak. To avoid this, in a proper exception handling
mechanism we can return all the resources which are previously allocated by the
system, to the sysem. So each exception
must be handled separately by keeping in mind when they might possibly occur.
Try Block
The try block consists of
a set of executable statements that can possibly throw exception while
executing them. A method, which may
throw an exception can also be included in the try block. A try block can be followed by one or more
catch blocks where exception thrown in the try block is caught. On the other hand, a try( ) block may not be
followed by a catch ( ) block as follows:
int demo = 0;
try {
System.out.println(20/demo);
}
the statement
System.out.println(20/demo); will throw an exception because we are trying to
ddivide a number by zero. The program
compilation will be successful, but on execution the program will be
terminated. This because the exception
is thrown at run time.
Catch Block
The catch block catches
the exceptions thrown in the try block.
Without the try block no catch block can exist. We can have multiple catch blocks covering
different types of exceptions.
Example 1(Exception)
class TryClass{
public static void main(String
args[]){
int demo=0;
try{
System.out.println(20/demo);
}
catch(ArithmeticException a){
System.out.println(“Can not
Divide Zero “);
}
}
}
In above program we are trying to
divide a number by zero which is not a valid arithmetic operation. Hence, an exception is thrown which is caught
in the caught in the catch block provided.
Throws Clause
In java when an error condition
ariases in a program, we send an exception up the call chain by using the throw
keyword. The java exception class
implements the Throwable interface and provides some useful features for
dealing with exceptions. It is often useful
to create our own exception class for special case exception handling within
the program. This is normally done by
creating a subclass of the exception class.
The advantage of the sub-classing the exception class is that, the new
exception type can be caught separately from other Throwable types.
Example 2(Throws Exception)
import java.io.*;
public class ThrowsDemo{
public static void main(String args[])throws
IOException,NumberFormatException{
double aimedAmt;
double interest=7.5;
double payment;
int years=0;
double balance=0;
InputStreamReader isr = new
InputStreamReader(System.in);
BufferedReader br= new
BufferedReader(isr);
System.out.print("Amout to
be expected at the time of retirement ");
aimedAmt=Double.valueOf(br.readLine(
)).doubleValue( );
System.out.println("
");
System.out.print("Your
Contribution In each year ");
payment=Double.valueOf(br.readLine(
)).doubleValue( );
System.out.println("
");
while(balance<aimedAmt){
balance=(balance+payment)*(1+(interest/100));
years++;
}
System.out.println("You Can
Retire in "+years+"Years.");
}
}
Throw keyword
Throw keyword is used to indicate
that exception has occurred. The operand
of throw is an object of a class, which is derived from class Throwable.
Example 3(Throw Exception)
class ArraySizeException extends
NegativeArraySizeException{
ArraySizeException( ){
super("Illegal Array Size
");
}
}
class ThrowDemo{
int size,arr[];
ThrowDemo(int s){
size=s;
try{
checkSize( );
}
catch(ArraySizeException e){
System.out.println(e);
}
}
void checkSize( ) throws
ArraySizeException{
if(size<0)
throw new ArraySizeException( );
arr=new int[3];
for(int i=0;i<3;i++)
arr[i]=i+1;
}
public static void main(String args[])
{
new
ThrowDemo(Integer.parseInt(args[0]));
}
}
Finally Block
Finally block is the block in
which we find statements which return resources to the system and other
statements for printing any message.
Typically, these statements include
Ø
Closing a file
Ø
Closing a resultset(Used in Database
programming)
Ø
Closing a connection established with the database
This block is optional but when
included is placed after the last catch block of a try( ). The finally block always executed no
matter whether exception is thrown or not.
If in a try block, a return or a breack statement is used, then
on executing that statement, the control comes to first statement of the
finally block.
The above figure Denotes two
possibilities one when not exception, then the control directly execute the
finally block. And in second situation it catch the error and then passes
the control to finally block.
Example 4(Finally)
class FinallyDemo
{
String name;
int no1,no2;
FinallyDemo(String args[])
{
try
{
name = new String("Leenas
Software");
no1= Integer.parseInt(args[0]);
no2= Integer.parseInt(args[1]);
System.out.println(name);
System.out.println("Division
Result is "+no1/no2);
}
catch(ArithmeticException i)
{
System.out.println("Can not
devide by Zero ");
}
finally{
name = null;
System.out.println("Finally
excecuted ");
}
}
public static void main(String args[])
{
new FinallyDemo(args);
}
}
Example 1
(ArrayIndexOutOfBoundsException)
public class CatchExp{
public static void main(String args[])
{
int []arr=new int[10];
try{
arr[11]=10;
}
catch(ArrayIndexOutOfBoundsException
e)
{
e = new
ArrayIndexOutOfBoundsException(" \t\tHello Notice the Length of the
Array");
throw(e);
}
}
}
Example 2 (Divide By Zero
Exception)
import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;
public class divZero extends Applet
implements ActionListener
{
Label l1,l2;
TextField tf1,tf2;
int num1,num2;
double result;
public void init( )
{
l1= new Label("Enter
Numerator :");
tf1 = new TextField(10);
l2= new Label("Enter
Denominator and press Enter :");
tf2 = new TextField(10);
add(l1);
add(l2);
add(tf1);
add(tf2);
tf2.addActionListener(this);
}
public void
actionPerformed(ActionEvent ae){
num1=Integer.parseInt(tf1.getText());
tf1.setText(" ");
num2=Integer.parseInt(tf2.getText());
tf2.setText(" ");
try
{
result =quotient(num1,num2);
showStatus(num1 +" / "
+ num2 + " = " +Double.toString(result));
}
catch(ArithmeticException e){
showStatus (e.toString());
}
}
public double quotient(int
numerator, int denominator)throws ArithmeticException
{
if(denominator ==0)
throw new ArithmeticException();
return(double)numerator/denominator;
}
}
Example 3 (Using the Exception)
class UseExp{
public static void main(String
args[]){
try{
throwException( );
}
catch(Exception e){
System.err.println("Exception
Handled in Main ");
}
doesNotThrowException( );
}
public static void
throwException() throws Exception
{
try{
System.out.println("Method
throwsException");
throw new Exception( );
}
catch(Exception e){
System.err.println("Exception
handled in Method throws Exception");
throw e;
}
finally{
System.err.println("Finally
is always Executed");
}
}
public static void
doesNotThrowException( ){
try{
System.out.println("Method
Does not Throw Exception ");
}
catch(Exception e){
System.out.println(e.toString(
));
}
finally{
System.out.println("Finally
is always executed");
}
}
}
Subscribe to:
Posts (Atom)