Java Programming Ch5 Ch6
Java Programming Ch5 Ch6
Topic 5
Java Applets & Graphics Programming
Total Marks- 20
Specific Objectives:
The students will be able to write interactive applets and make use of graphics in
programming.
They will also learn to change the background and the foreground color and to use the
different fonts.
Contents:
5.1 Introduction to applets Applet, Applet life cycle (skeleton), Applet tag, Adding Applet
To HTML file, passing parameter to applet, embedding <applet>tags in java code, adding
controls to applets.
5.2 Graphics Programming Graphics classes, lines, rectangles, ellipse, circle, arcs,
polygons, color & fonts, setColor(), getColor(), setForeGround(), setBackGround(), font
class, variable defined by font class: name, pointSize, size, style, font methods: getFamily(),
getFont(), getFontname(), getSize(), getStyle(), getAllFonts() &
getavailablefontfamilyname() of the graphics environment class.
JPR-17515 Page 2
Topic 5. Java Applets & Graphics Programming
Applet Basics-
Basically, an applet is dynamic and interactive java program that inside the web
page or applets are small java programs that are primarily used in internet computing. The
java application programs run on command prompt using java interpreter whereas
the java applets can be transported over the internet form one computer to another and run
using the appletviewer or any web browser that supports java.
An applet is like application program which can perform arithmetic
operations, display graphics, play sounds accept user input, create animation and
play interactive games. To run an applet, it must be included in HTML tags for web page.
Web browser is a program to view web page.
Every applet is implemented by creating sub class of Applet class.
Following diagram shows the inheritance hierarchy of Applet class.
java.lang.Object
java.awt.Component
java.awt.Container
java.awt.Panel
java.applet.Applet
Fig. Chain of classes inherited by Applet class in java
5.1.1 Differentiate between applet and application (4 points). [W-14, S-15, W-15 ]
Applet Application
Applet does not use main() method for Application use main() method for initiating
initiating execution of code execution of code
Applet cannot run independently Application can run independently
Applet cannot read from or write to files in Application can read from or write to files in
local computer local computer
Applet cannot communicate with other Application can communicate with other
servers on network servers on network
Applet cannot run any program from local Application can run any program from local
computer. computer.
Applet are restricted from using libraries Application are not restricted from using
from other language such as C or C++ libraries from other language
JPR-17515 Page 3
Topic 5. Java Applets & Graphics Programming
Applet enters the running state when the system calls the start() method
of Applet class. This occurs automatically after the applet is initialized. start() can also
be called if the applet is already in idle state. start() may be called more than once.
start() method may be overridden to create a thread to control the applet.
JPR-17515 Page 4
Topic 5. Java Applets & Graphics Programming
APPLET Tag:
The APPLET tag is used to start an applet from both an HTML document and
from an applet viewer.
<APPLET
[CODEBASE = codebaseURL]
CODE = appletFile
[ALT = alternateText]
[NAME = appletInstanceName]
WIDTH = pixels HEIGHT = pixels
[ALIGN = alignment]
[VSPACE = pixels] [HSPACE = pixels]>
[< PARAM NAME = AttributeName1 VALUE = AttributeValue>]
[<PARAM NAME = AttributeName2 VALUE = AttributeValue>]
...
</APPLET>
JPR-17515 Page 5
Topic 5. Java Applets & Graphics Programming
CODEBASE is an optional attribute that specifies the base URL of the applet code or
the directory that will be searched for the applet‟s executable class file.
CODE is a required attribute that give the name of the file containing your applet‟s
compiled class file which will be run by web browser or appletviewer.
ALT: Alternate Text. The ALT tag is an optional attribute used to specify a short text
message that should be displayed if the browser cannot run java applets.
NAME is an optional attribute used to specifies a name for the applet instance.
WIDTH AND HEIGHT are required attributes that give the size(in pixels) of the
applet display area.
VSPACE AND HSPACE attributes are optional, VSPACE specifies the space, in
pixels, about and below the applet. HSPACE VSPACE specifies the space, in
pixels, on each side of the applet
PARAM NAME AND VALUE: The PARAM tag allows you to specifies applet-
specific arguments in an HTML page applets access there attributes with the
get Parameter()method.
Example
import java.awt.*;
import java.applet.*;
JPR-17515 Page 6
Topic 5. Java Applets & Graphics Programming
{
String str;
public void init()
{
str = getParameter("username");
str = "Hello "+ str;
}
public void paint(Graphics g)
{
g.drawString(str,10,100);
}
}
<HTML>
<Applet code = ―hellouser.class‖ width = 400 height = 400>
<PARAM NAME = "username" VALUE = abc>
</Applet>
</HTML>
The Applet tag in HTML document allows passing the arguments using param tag.
The syntax of <PARAM…> tag
JPR-17515 Page 7
Topic 5. Java Applets & Graphics Programming
Program for an applet to accept user name in the form of parameter and print
„Hello<username>‟ [W-15]
import java.awt.*;
import java.applet.*;
<HTML>
<Applet code = ―hellouser.class‖ width = 400 height = 400>
<PARAM NAME = "username" VALUE = abc>
</Applet>
</HTML>
Graphics can be drawn with the help of java. java applets are written to
draw lines, figures of different shapes, images and text in different styles even
with the colours in display.
Every applet has its own area of the screen known as canvas, where it creates the
display in the area specified the size of applet‘s space is decided by the attributes of
<APPLET...> tag.
A java applet draws graphical image inside its space using the coordinate system
shown in following fig., which shows java‘s coordinate system has the origin (0, 0) in
the upper-left corner, positive x values are to be right, and positive y values are to the
bottom. The values of coordinates x and y are in pixels.
X
(0, 0)
JPR-17515 Page 8
Topic 5. Java Applets & Graphics Programming
1. Write a java applet code and save it with as a class name declared in a program by
extension as a .java.
e.g. from above java code file we can save as a Welcome.java
3. After successfully compiling java file, it will create the .class file, e.g
Welcome.class. then we have to write applet code to add this class into applet.
4. Applet code
<html>
<Applet code= ― Welcome.class‖ width= 500 height=500>
</applet>
</html>
5. Save this file with Welcome.html in ‗bin‘ library folder.
The Graphics class of java includes methods for drawing different types
of shapes, from simple lines to polygons to text in a variety of fonts.
JPR-17515 Page 9
Topic 5. Java Applets & Graphics Programming
Method Description
clearRect( ) Erases a rectangular area of the canvas
copyArea( ) Copies a rectangular area of the canvas to another area
drawArc( ) Draws a hollow arc.
drawLine( ) Draws a straight line
drawOval( ) Draws a hollow oval
drawPolygon( ) Draws a hollow polygon
drawRect( ) Draws a hollow rectangle
drawRoundRect( ) Draws a hollow rectangle with rounded corners.
drawstring( ) Displays a text string
fillArc( ) Draws a filled arc
fillOval( ) Draws a filled arc
fillPolygon( ) Draws a filled polygon
fillRect( ) Draws a filled rectangle
fillRoundRect( ) Draws filled rectangle with rounded corners
getColor( ) Retrieves the current drawing color
getFont( ) Retrieves the currently used font
getFontMetrics( ) Retrieves information about the current font.
setColor( ) Sets the drawing color
setFont( ) Seta fonts.
Displaying String:
drawString() method is used to display the string in an applet window
Syntax:
void drawString(String message, int x, int y);
where message is the string to be displayed beginning at x, y
Example:
g.drawString(―WELCOME‖, 10, 10);
JPR-17515 Page 10
Topic 5. Java Applets & Graphics Programming
5.2.3.1. drawLine( )
The drawLine ( ) method is used to draw line which takes two pair
of
coordinates (x1,y1) and (x2, y2) as arguments and draws a line between
them. The graphics object g is passed to paint( ) method.
The syntax is
g.drawLine(x1,y1,x2,y2);
e.g. g.drawLine(20,20,80,80);
Syntax: void drawRect(int top, int left, int width, int height)
This method takes four arguments, the first two represents the x and y
co- ordinates of the top left corner of the rectangle and the remaining two represent the
width and height of rectangle.
Example: g.drawRect(10,10,60,50);
Q. Design an Applet program which displays a rectangle filled with red color
and message as “Hello Third year Students” in blue color. [S-16]
Program-
import java.awt.*;
import java.applet.*;
g.setColor(Color.blue);
g.drawString("Hello Third year Students",70,100);
}
}
JPR-17515 Page 11
Topic 5. Java Applets & Graphics Programming
Syntax: void drawOval( int top, int left, int width, int height)
Example: g.drawOval(10,10,50,50);
Syntax- void fillOval(int top, int left, int width, int height):
Example g.fillOval(10,10,50,50);
Q. Write a simple applet program which display three concentric circle. [S-16]
Program-
import java.awt.*;
import java.applet.*;
g.drawOval(100,100,190,190);
g.drawOval(115,115,160,160);
g.drawOval(130,130,130,130);
}
}
(OR)
HTML Source:
<html> <applet code=‖CircleDemo.class‖ height=300 width=200>
</applet>
</html>
JPR-17515 Page 12
Topic 5. Java Applets & Graphics Programming
Q. Write a program to design an applet to display three circles filled with three
different colors on screen. [ W-14, W-15 ]
Program-
import java.awt.*;
import java.applet.*;
g.setColor(Color.green);
g.fillOval(50,150,100,100);
g.setColor(Color.yellow);
g.fillOval(50,250,100,100);
}
}
Output
JPR-17515 Page 13
Topic 5. Java Applets & Graphics Programming
where x, y starting point, w& h are width and height of arc, and start_angle is
starting angle of arc sweep_angle is degree around the arc
Example:
g.drawArc(10, 10, 30, 40, 40, 90);
g.drawPolygon(x, y, n);
Q. Write the syntax and example for each of following graphics methods:
1) drawPoly ( ) 2) drawRect ( ) 3) drawOval ( ) 4) fillOval ( )
For syntax refer above 5.2.3.2 and all........
import java.applet.*;
import java.awt.*;
/*
<applet code = DrawGraphics.class height = 500 width = 400>
</applet>*/
JPR-17515 Page 14
Topic 5. Java Applets & Graphics Programming
void setBackground(Color.newColor)
where newColor specifies the new color. The class color defines the constant
for specific color listed below.
setForeground (Color.yellow);
The following methods are used to retrieve the current background and foreground
color.
Color getBackground( )
Color getForeground( )
A font determines look of the text when it is painted. Font is used while painting text
on a graphics context & is a property of AWT component.
Variable Meaning
String name Name of the font
float pointSize Size of the font in points
int size Size of the font in point
int style Font style
The Font class states fonts, which are used to render text in a visible way.
It is used to set or retrieve the screen font.
To select a new font, you must first construct a Font object that describes that
font. Font constructor has this general form:
JPR-17515 Page 15
Topic 5. Java Applets & Graphics Programming
fontName specifies the name of the desired font. The name can be specified
using either the logical or face name.
All Java environments will support the following fonts:
Dialog, DialogInput, Sans Serif, Serif, Monospaced, and Symbol. Dialog is the
font used by once system‟s dialog boxes.
Dialog is also the default if you don‟t explicitly set a font. You can also use
any other fonts supported by particular environment, but be careful—these other fonts
may not be universally available.
The style of the font is specified by fontStyle. It may consist of one or more of
these three constants:
Font.PLAIN, Font.BOLD, and Font.ITALIC. To combine styles, OR
them together.
For example,
Font.BOLD | Font.ITALIC specifies a bold, italics style.
The size, in points, of the font is specified by pointSize.
To use a font that you have created, you must select it using setFont( ), which
is defined by Component.
It has this general form:
void setFont(Font fontObj)
Here, fontObj is the object that contains the desired font
Q. Describe any three methods of font class with their syntax and example
of each. [W-14, S-15 ]
Sr.
Methods Description
No
1 static Font decode(String str) Returns a font given its name.
Returns true if the invoking object contains the
boolean equals(Object
2 same font as that specified by FontObj.Otherwise,
FontObj) :
it returns false.
3 String toString( ) Returns the string equivalent of the invoking font.
Returns the name of the font family to which the
4 String getFamily( )
invoking font belongs.
Returns the font associated with the system
static Font getFont(String
5 property specified by property. null is returned if
property)
property does not exist.
Returns the font associated with the System
static Font getFont(String property specified by property.
6
property,Font defaultFont) The font specified by defaultFont is returned if
property does not exist.
7 String getFontName( ) Returns the face name of the invoking font.
8 String getName( ) Returns the logical name of the invoking font.
JPR-17515 Page 16
Topic 5. Java Applets & Graphics Programming
Example:-
import java.awt.*;
import java.applet.*;
import java.awt.*;
import java.applet.*;
Q. Write method to set font of a text and describe its parameters. [S-16]
The AWT supports multiple type fonts emerged from the domain of traditional
type setting to become an important part of computer-generated documents and
displays. The AWT provides flexibility by abstracting font-manipulation
operations and allowing for dynamic selection of fonts.
Fonts have a family name, a logical font name, and a face name. The family
name is the general name of the font, such as Courier. The logical name specifies a
category of font, such as Monospaced. The face name specifies a specific font, such as
Courier Italic To select a new font, you must first construct a Font object that
describes that font.
One Font constructor has this general form:
Font(String fontName, intfontStyle, intpointSize)
To use a font that you have created, you must select it using setFont( ), which
is defined by Component.
It has this general form:
void setFont(Font fontObj)
Example
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class SampleFonts extends Applet
{
int next = 0;
Font f;
String msg;
JPR-17515 Page 18
Topic 5. Java Applets & Graphics Programming
Syntax:
public abstract String[ ] getAvailableFontFamilyNames(Locale 1)
Parameters:
l - a Locale object that represents a particular geographical, political, or
cultural region. Specifying null is equivalent to specifying Locale.getDefault().
Or
String[ ] getAvailableFontFamilyNames( )
It will return an array of strings that contains the names of the available font families
Important Questions:-
4 Marks Questions:-
1) Write syntax and example of 1) drawString ( ) 2) drawRect ( ) ; 3) drawOval ( )
4) drawArc ( ).
2) Describe following states of applet life cycle : a) Initialization state. b) Running state.
c) Display state
3) State the use of font class. Describe any three methods of font class with their syntax
and example of each.
4) Differentiate applet and application with any four points.
5) State syntax and explain it with parameters for : i)drawRect ( ) ii) drawOral ( )
6) Design an Applet program which displays a rectangle filled with red color and
message as ―Hello Third year Students‖ in blue color.
7) Describe applet life cycle with suitable diagram.
8) Differentiate between applet and application (any 4 points).
9) Write a program to design an applet to display three circles filled with three different
colors on screen.
10) Explain all attributes available in < applet > tag.
JPR-17515 Page 19
Topic 5. Java Applets & Graphics Programming
JPR-17515 Page 20
Topic 6. File I/O & collection frame work
1. What are stream classes ? List any two input stream classes from character stream
[S-15, S-16]
Definition:
The java. IO package contain a large number of stream classes that provide
capabilities for processing all types of data. These classes may be categorized into two
groups based on the data type on which they operate.
1. Byte stream classes that provide support for handling I/O operations on bytes.
2. Character stream classes that provide support for managing I/O operations on
characters.
Character Stream Class can be used to read and write 16-bit Unicode
characters. There are two kinds of character stream classes, namely, reader stream classes
and writer stream classes
JPR-17515 Page 20
Topic 6. File I/O & collection frame work
2. What are streams ? Write any two methods of character stream classes. [W-15]
Java programs perform I/O through streams. A stream is an abstraction that either
produces or consumes information (i.e it takes the input or gives the output). A stream is
linked to a physical device by the Java I/O system.
All streams behave in the same manner, even if the actual physical devices
to which they are linked differ. Thus, the same I/O classes and methods can be applied to
any type of device.
Java 2 defines two types of streams: byte and character.
Byte streams provide a convenient means for handling input and output of bytes.
Byte streams are used, for example, when reading or writing binary data.
Character streams provide a convenient means for handling input and output
of characters.
They use Unicode and, therefore, can be internationalized. Also, in some
cases, character streams are more efficient than byte streams.
JPR-17515 Page 21
Topic 6. File I/O & collection frame work
4) int read(char buffer[ ]) : Attempts to read up to buffer. Length characters into buffer
and returns the actual number of characters that were successfully read. –1 is returned when
the end of the file is encountered.
5) abstract int read(char buffer[ ],int offset,int numChars): Attempts to read up
to numChars characters into buffer starting at buffer[offset], returning the number of
characters successfully read.–1 is returned when the end of the file is encountered.
6) boolean ready( ): Returns true if the next input request will not wait. Otherwise, it
returns false.
7) void reset( ): Resets the input pointer to the previously set mark.
8) long skip(long numChars) :- Skips over numChars characters of input, returning the
number of characters actually skipped.
9) abstract void close( ) :- Closes the input source. Further read attempts will generate an
IOException
Writer Class
Writer is an abstract class that defines streaming character output. All of the methods
in this class return a void value and throw an IOException in the case of error
2) abstract void flush( ) : Finalizes the output state so that any buffers are cleared. That
is, it flushes the output buffers.
3) void write(intch): Writes a single character to the invoking output stream. Note that the
parameter is an int, which allows you to call write with expressions without having to cast
them back to char.
5) abstract void write(char buffer[ ],int offset, int numChars) :- Writes a subrange of
numChars characters from the array buffer, beginning at buffer[offset] to the invoking output
stream.
7) void write(String str, int offset,int numChars): Writes a sub range of numChars
characters from the array str, beginning at the specified offset.
JPR-17515 Page 22
Topic 6. File I/O & collection frame work
3. What is use of stream classes ? Write any two methods FileReader class.[W-14]
2. public int read(char[ ] cbuf, int offset, int length) throws IOException -
Reads characters into a portion of an array.
3. public void close()throws IOException - Closes the stream and releases any
system resources associated with it. Once the stream has been closed, further
read(), ready(), mark(), reset(), or skip() invocations will throw an IOException.
Closing a previously closed stream has no effect
6. public void reset()throws IOException - Resets the stream. If the stream has been
marked, then attempt to reposition it at the mark. If the stream has not
been marked, then attempt to reset it in some way appropriate to the particular
stream, for example by repositioning it to its starting point. Not all character-input
streams support the reset() operation, and some support reset() without supporting
mark().
4. Write any two methods of File and FileInputStream class each.[S-15, W-15]
3. boolean exists( ) - returns true if the file exists, false if it does not.
4. void deleteOnExit( ) -Removes the file associated with the invoking object when
the Java Virtual Machine terminates.
5. boolean isHidden( )-Returns true if the invoking file is hidden. Returns false
otherwise.
1. int available( )- Returns the number of bytes of input currently available for
reading.
2. void close( )- Closes the input source. Further read attempts will generate an
IOException.
3. void mark(int numBytes) -Places a mark at the current point in the inputstream
that will remain valid until numBytes bytes are read.
4. boolean markSupported( ) -Returns true if mark( )/reset( ) are supported by the
invoking stream.
5. int read( )- Returns an integer representation of the next available byte of input. –1
is returned when the end of the file is encountered.
6. int read(byte buffer[ ])- Attempts to read up to buffer.length bytes into buffer and
returns the actual number of bytes that were successfully read. –1 is returned when the end of
the file is encountered.
Serialization is the process of writing the state of an object to a byte stream. This is
useful when you want to save the state of your program to a persistent storage area, such
as a file. At a later time, you may restore these objects by using the process of
deserialization.
Example:
Assume that an object to be serialized has references to other objects, which,
inturn, have references to still more objects. This set of objects and the
relationships among them form a directed graph. There may also be circular
references within this object graph. That is, object X may contain a reference to
object Y, and object Y may contain a reference back to object X. Objects may also
contain references to themselves. The object serialization and deserialization facilities
have been designed to work correctly in these scenarios. If you attempt to serialize an
object at the top of an object graph, all of the other referenced objects are recursively
located and serialized. Similarly, during the process of deserialization, all of these objects
and their references are correctly restored.
JPR-17515 Page 24
Topic 6. File I/O & collection frame work
6. Write a program to copy contents of one file to another file using character stream
class.[S-15]
import java.io.*;
class CopyData
{
public static void main(String args[ ])
{
//Declare input and output file stream
byte byteRead;
try
{
// connect fis to in.dat
fis=new FileInputSream(―in.dat‖);
// connect fos to out.dat
fos= new FileOutputStream(―out.dat‖);
//reading bytes from in.dat and write to out.dat
do
{
byteRead =(byte)fis.read( );
fos.write(byteRead);
}
while(byteRead != -1);
}
Catch(FileNotFoundException e)
{
System.out.println(―file not found‖);
}
Catch(IOException e)
{
System.out.pritln(e.getMessage( ));
}
finally // close file
{
JPR-17515 Page 25
Topic 6. File I/O & collection frame work
try
{
fis.close( );
fos.close( );
}
Catch(IOException e)
{ }
}
}
}
7. What is use of ArrayList Class ? State any three methods with their use from
ArrayList.[W-15, S-16]
1. void add(int index, Object element) Inserts the specified element at the specified
position index in this list. Throws IndexOutOfBoundsException if the specified index
is is out of range (index < 0 || index >size()).
2. boolean add(Object o) Appends the specified element to the end of this list.
JPR-17515 Page 26
Topic 6. File I/O & collection frame work
7. boolean contains(Object o) Returns true if this list contains the specified element.
More formally, returns true if and only if this list contains at least one element e such
that (o==null ? e==null : o.equals(e)).
9. Object get(int index) Returns the element at the specified position in this
list. Throws IndexOutOfBoundsException if the specified index is is out of range
(index <
0 || index >= size()).
10. intindexOf(Object o) Returns the index in this list of the first occurrence of the
specified element, or -1 if the List does not contain this element.
11. intlastIndexOf(Object o) Returns the index in this list of the last occurrence of
the specified element, or -1 if the list does not contain this element.
12. Object remove(int index) Removes the element at the specified position in this
list. Throws IndexOutOfBoundsException if index out of range (index < 0 || index >=
size()).
14. Object set(int index, Object element) Replaces the element at the
specified position in this list with the specified element. Throws
IndexOutOfBoundsException if the specified index is is out of range (index < 0 ||
index >= size()).
16. Object[ ] toArray() Returns an array containing all of the elements in this list in
the correct order. Throws NullPointerException if the specified array is null.
18. void trimToSize() Trims the capacity of this ArrayList instance to be the
list's current size.
JPR-17515 Page 27
Topic 6. File I/O & collection frame work
ii. getDate()
Syntax:
public int getDate()
Returns the day of the month. This method assigns days with the values of
1 to 31.
1. setTime():
2.getDay()
int getDay():
Returns the day of the week represented by this date.
The returned value (0 = Sunday, 1 = Monday, 2 = Tuesday, 3 = Wednesday, 4 =
Thursday, 5 = Friday, 6 = Saturday) represents the day of the week that contains or
begins with the instant in time represented by this Date object, as interpreted in the
local time zone.
2) max() :
Syntax: static int max(int a, int b)
Use: This method returns the greater of two int values.
3) sqrt()
Syntax: static double sqrt(double a)
Use : This method returns the correctly rounded positive square root of a double
JPR-17515 Page 28
Topic 6. File I/O & collection frame work
value.
4) pow() :
Syntax: static double pow(double a, double b)
Use : This method returns the value of the first argument raised to the power of the
second argument.
5) exp()
Syntax: static double exp(double a)
Use : This method returns Euler's number e raised to the power of a double value.
6) round() :
Syntax: static int round(float a)
Use : This method returns the closest int to the argument.
7) abs()
Syntax: static int abs(int a)
Use : This method returns the absolute value of an int value.
JPR-17515 Page 29
Topic 6. File I/O & collection frame work
import java.util.*;
public class SetDemo
{
public static void main(String args[])
{
int count[] = {34, 22,10,60,30,22};
Set<Integer> set = new HashSet<Integer>();
try{
for(int i = 0; i<5; i++){
set.add(count[i]);
}
System.out.println(set);
TreeSet sortedSet = new TreeSet<Integer>(set);
System.out.println("The sorted list is:");
System.out.println(sortedSet);
System.out.println("The First element of the set is: "+ (Integer)sortedSet.first());
System.out.println("The last element of the set is: "+ (Integer)sortedSet.last());
}
catch(Exception e){}
}
}
12. State syntax and describe any two methods of map class.[S-16]
The Map Classes Several classes provide implementations of the map interfaces. A
map is an object that stores associations between keys and values, or key/value pairs.
Given a key, you can find its value. Both keys and values are objects. The keys must be
unique, but the values may be duplicated. Some maps can accept a null key and
null values, others cannot.
Methods:
void clear // removes all of the mapping from map
booleancontainsKey(Object key) //Returns true if this map contains a mapping for the
specified key.
Boolean conainsValue(Object value)// Returns true if this map maps one or more keys to
the specified value
Boolean equals(Object o) //Compares the specified object with this map for equality
JPR-17515 Page 30