3. Introduction
Prof. K. Adisesha
3
Java Graphics:
The Graphics class is the abstract super class for all graphics contexts which allow an
application to draw onto components that can be realized on various devices, or onto off-
screen images as well.
➢ A Graphics object encapsulates all state information required for the basic rendering
operations that Java supports. State information includes the following properties.
❖ The Component object on which to draw.
❖ A translation origin for rendering and clipping coordinates.
❖ The current clip.
❖ The current color.
❖ The current font.
❖ The current logical pixel operation function.
4. Introduction
Prof. K. Adisesha
4
Window Fundamentals:
Java Abstract window tool kit package is used for displaying the data within a GUI
Environment. Features of AW T Package are as Followings.
➢ The main purpose for using the AWT is using for all the components displaying on the screen.
➢ It provides us a set of user interface components
including windows buttons text fields scrolling
list etc.
➢ It provides us the way to laying out these above
components.
➢ It provides to create the events upon these
components.
5. Introduction
Prof. K. Adisesha
5
Graphical User Interface:
Graphical User Interface (GUI) offers user interaction via some graphical components.
➢ Components: underlying Operating System offers GUI via window, frame, Panel, Button, Textfield,
TextArea, Listbox, Combobox, Label, Checkbox etc.
➢ Container: Container object is a component that can contain other components. Components added to a
container are tracked in a list.
➢ Panel: Panel provides space in which an application can attach any other components, including other
panels.
➢ Window: Window is a rectangular area which is displayed on the screen. Window provide us with
multitasking environment.
➢ Frame: A Frame is a top-level window with a title and a border. The size of the frame includes any area
designated for the border.
➢ Canvas: Canvas component represents a blank rectangular area of the screen onto which the application
can draw.
6. Introduction
Prof. K. Adisesha
6
Java AWT Graphics:
Graphics is an abstract class provided by Java AWT (Abstract Window Toolkit), which is
used to draw or paint on the components.
➢ It consists of various fields which hold information like components to be painted, font,
color, etc., and methods that allow drawing various shapes on the GUI components.
➢ Graphics is an abstract class and thus cannot be initialized directly.
➢ Objects of its child classes can be obtained in the following two ways.
❖ Inside paint() or update() method.
❖ getGraphics() method. //Following is the declaration for java.awt.Component class:
public abstract class Component
extends Object
implements ImageObserver, MenuContainer, Serializable
7. AWT Graphics Class
Prof. K. Adisesha
7
Java AWT Graphics:
Graphics is an abstract class provided by Java AWT which is used to draw or paint on
the components.
➢ Inside paint() or update() method: It is passed as an argument to paint and update methods and
therefore can be accessed inside these methods are present in the Component class and can be
overridden for the component to be painted.
❖ void paint(Graphics g)
❖ void update(Graphics g)
➢ getGraphics() method: This method is present in the Component class and thus can be called on
any Component in order to get the Graphics object for the component.
❖ public Graphics getGraphics(): Creates a graphics context for the component and will
return null if the component is currently not displayable. Graphics g = f.getGraphics();
public void paint(Graphics g)
{ g.drawRect(100, 100, 100, 50); }
8. AWT Graphics Class
Prof. K. Adisesha
8
Java - Applet:
Graphics is an abstract class provided by Java AWT which is used to draw or paint on
the components.
➢ Class declaration: Following is the declaration for java.awt.Graphics class:
public abstract class Graphics
extends Object
➢ Class constructors: Following is the declaration for Constructs a new Graphics object:
Graphics() { }
Example: Following is the declaration for java.awt.Component class:
public abstract class Component
extends Object
implements ImageObserver, MenuContainer, Serializable
9. AWT Graphics Class
Prof. K. Adisesha
9
Constructor & methods:
Graphics(): It is used to create an object by using the new keyword.
➢ Frequently used methods:
❖ drawString(String str, int x, int y): It is used to draw a given string within the coordinates.
❖ drawRect(int x, int y, int width, int height): It is used to draw a rectangle with given width
and height.
❖ drawLine(int x1, int y1, int x2, int y2): It is used to draw a line with x1, y1, and x2, y2
points.
❖ drawImage(Image img, int x, int y, ImageObserver observer): It is used to draw the image.
❖ drawArc(int x, int y, int width, int height, intstartAngle, intarcAngle): It is used to draw an
elliptical or circular shape.
❖ fillArc(int x, int y, int width, int height, intstartAngle, intarcAngle): It is used to fill the
circular shape or elliptical shape arc.
10. AWT Graphics Class
Prof. K. Adisesha
10
Constructor & methods:
Graphics(): It is used to create an object by using the new keyword.
➢ Frequently used methods:
❖ setColor(Color c): It is used to set given color.
❖ setFont(Font font): It is used to set specified font.
❖ fillRect(int x, int y, int width, int height): It is used to fill the rectangle with the given color
by provided coordinates and width, height to the rectangle.
❖ drawOval(int x, int y, int width, int height): It is used to draw an oval shape with the given
width and height.
❖ fillOval(int x, int y, int width, int height): It is used to fill the oval shape with the color and
specified width and height.
11. AWT Graphics Class
Prof. K. Adisesha
11
Constructor & methods:
The drawXxx() methods draw the outlines; while fillXxx() methods fill the internal.
➢ Frequently used methods:
12. AWT Graphics Class
Prof. K. Adisesha
12
Example: MyFrame.java
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class MyFrame extends Frame
{ public MyFrame()
{ setVisible(true);
setSize(300, 200);
addWindowListener(new WindowAdapter()
{ @Override
public void windowClosing(WindowEvent e)
{ System.exit(0); }
});
}
public void paint(Graphics g)
{ g.drawRect(100, 100, 100, 50); }
public static void main(String[] args)
{ new MyFrame(); }
}
13. AWT Graphics Class
Prof. K. Adisesha
13
Lines are drawn by means of the drawLine() method.
//Drawing Lines
import java.awt.*;
import java.applet.*;
/*
<applet code="Lines" width=300 Height=250>
</applet> */
public class Lines extends Applet
{ 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(5,290,80,19);
}
}
14. AWT Graphics Class
Prof. K. Adisesha
14
Lines are drawn by the method for circles or ellipses.
import java.awt.*;
import java.applet.*;
/*
<applet code="Ellipses" width=300 Height=300>
</applet>*/
public class Ellipses extends Applet
{ public void paint(Graphics g)
{
g.drawOval(10,10,60,50);
g.fillOval(100,10,75,50);
g.drawOval(190,10,90,30);
g.fillOval(70,90,140,100);
}
}
c:jdk1.4binjavac Ellipses.java
c:jdk1.4binappletviewer Ellipses.java
15. AWT Event Handling
Prof. K. Adisesha
15
Event :
Change in the state of an object is known as event i.e. event describes the change in state
of source.
➢ Events are generated as result of user interaction with the graphical user interface components.
➢ For example, clicking on a button, moving the mouse, entering a character through keyboard,
selecting an item from list, scrolling the page are the activities that causes an event to happen.
➢ Types of Event
❖ Foreground Events - Those events which require the direct interaction of user. They are
generated as consequences of a person interacting with the graphical components in
Graphical User Interface. For example, clicking on a button, moving the mouse.
❖ Background Events - Those events that require the interaction of end user are known as
background events. Operating system interrupts, hardware or software failure, timer
expires, are the example of background events.
16. AWT Event Handling
Prof. K. Adisesha
16
Event Handling:
Event Handling is the mechanism that controls the event and decides what should
happen if an event occurs.
➢ This mechanism have the code which is known as event handler that is executed when an event
occurs.
➢ Java Uses the Delegation Event Model to handle the events by defining the standard mechanism
to generate and handle the events.
➢ The Delegation Event Model has the following key participants namely:
❖ Source - The source is an object on which event occurs. It is responsible for providing
information of the occurred event to it's handler.
❖ Listener - It is also known as event handler. It is responsible for generating response to an
event. Listener waits until it receives an event. Once the event is received, the listener
process the event an then returns.
17. AWT Event Handling
Prof. K. Adisesha
17
AWT Event Classes:
The Event classes represent the event. Java provides us various Event classes but we will
discuss those which are more frequently used.
➢ EventObject class: This class is defined in java.util package. It is the root class from which all
event state objects shall be derived. All Events are constructed with a reference to the object.
➢ Class declaration: Following is the declaration for java.util.EventObject class:
public class EventObject
extends Object
implements Serializable
➢ Class methods: This class inherits methods from the following classes: java.lang.Object
❖ Object getSource(): The object on which the Event initially occurred.
❖ String toString(): Returns a String representation of this EventObject.
18. AWT Event Handling
Prof. K. Adisesha
18
AWT Event Listeners:
The Event listener represent the interfaces responsible to handle events.
➢ Every method of an event listener method has a single argument as an object which is subclass
of EventObject class.
➢ For example, mouse event listener methods will accept instance of MouseEvent, where
MouseEvent derives from EventObject.
➢ Class declaration: Following is the declaration for java.util.EventListener interface:
public interface EventListener
➢ Following is the list of commonly used event listeners.
❖ ActionListener, ComponentListener, ItemListener, KeyListener, MouseListener, TextListener,
WindowListener. AdjustmentListener, ContainerListener, MouseMotionListener
19. AWT Event Handling
Prof. K. Adisesha
19
AWT Event Adapters:
Adapters are abstract classes for receiving various events. The methods in these classes
are empty. These classes exists as convenience for creating listener objects.
➢ Following is the list of commonly used adapters while listening GUI events in AWT.
❖ FocusAdapter : An abstract adapter class for receiving focus events.
❖ KeyAdapter: An abstract adapter class for receiving key events.
❖ MouseAdapter: An abstract adapter class for receiving mouse events.
❖ MouseMotionAdapter: An abstract adapter class for receiving mouse motion events.
❖ WindowAdapter: An abstract adapter class for receiving window events.
➢Example: Following is the declaration for java.awt.event.FocusAdapter class:
public abstract class FocusAdapter
extends Object
implements FocusListener
20. Java Input/Output
Prof. K. Adisesha
20
Java Stream:
Java uses the concept of a stream to make I/O operation fast. The java.io package
contains all the classes required for input and output operations.
➢ In Java, a stream is composed of a sequence of data bytes. It's called a stream because it
is like a stream of water that continues to flow.
➢ In Java, 3 streams are created for us automatically. All these streams are attached with
the console.
❖ System.out: standard output stream
❖ System.in: standard input stream
❖ System.err: standard error stream.
22. Java Input/Output
Prof. K. Adisesha
22
Output Stream class:
OutputStream class is an abstract class. It is the superclass of all classes representing an
output stream of bytes.
➢ An output stream accepts output bytes and sends them to some sink.
➢ Useful methods of OutputStream
❖ public void write(int) throws IOException: is used to write a byte
to the current output stream.
❖ public void write(byte[]) throws IOException: is used to write an
array of byte to the current output stream.
❖ public void flush() throws IOException: flushes the current output
stream.
❖ public void close() throws IOException: is used to close the
current output stream.
23. Java Input/output
Prof. K. Adisesha
23
InputStream class:
InputStream class is an abstract class. It is the superclass of all classes representing an
input stream of bytes.
➢ An output stream accepts output bytes and sends them to some sink.
➢ Useful methods of InputStream
❖ public abstract int read() throws IOException: reads the next byte
of data from the input stream. It returns -1 at the end of the file.
❖ public int available() throws IOException: returns an estimate of
the number of bytes that can be read from the current input stream.
❖ public void close() throws IOException: is used to close the current
input stream.
24. Java File Stream
Prof. K. Adisesha
24
FileOutputStream:
Java FileOutputStream is an output stream used for writing data to a file.
➢ You can write byte-oriented as well as character-oriented data through FileOutputStream class.
➢ For character-oriented data, it is preferred to use FileWriter than FileOutputStream.
➢ FileOutputStream class declaration: public class FileOutputStream extends OutputStream
➢ FileOutputStream class methods:
❖ protected void finalize() It is used to clean up the connection with the file output stream.
❖ void write(byte[] ary) It is used to write ary.length bytes from the byte array to the file output
stream.
❖ void write(byte[] ary, int off, int len) It is used to write len bytes from the byte array starting at offset
off to the file output stream.
❖ void write(int b) It is used to write the specified byte to the file output stream.
❖ void close() It is used to closes the file output stream.
25. Java File Stream
Prof. K. Adisesha
25
FileOutputStream:
Java FileOutputStream is an output stream used for writing data to a file.
➢ Java FileOutputStream Example 1: write byte example 2: write string.
import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:f1.txt");
fout.write(15);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
}
import java.io.FileOutputStream;
public class FileOutputStreamExample
{ public static void main(String args[])
{ try
{ FileOutputStream fout=new FileOutputStream("D:f2.txt");
String s="Welcome to java Programming.";
byte b[]=s.getBytes();//converting string into byte array
fout.write(b);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
}
26. Java File Stream
Prof. K. Adisesha
26
FileInputStream Class:
Java FileInputStream class obtains input bytes from a file. It is used for reading byte-oriented
data (streams of raw bytes) such as image data, audio, video etc.
➢ You can also read character-stream data. But, it is recommended to use FileReader class.
➢ Class declaration: public class FileInputStream extends InputStream
➢ FileInputStream class methods:
❖ int read() It is used to read the byte of data from the input stream.
❖ int read(byte[] b) It is used to read up to b.length bytes of data from the input stream.
❖ long skip(long x) It is used to skip over and discards x bytes of data from the input stream.
❖ FileChannel getChannel() It is used to return the unique FileChannel object associated with the file
input stream.
❖ protected void finalize() It is used to ensure that the close method is call when there is no more
reference to the file input stream.
❖ void close() It is used to closes the stream.
27. Java File Stream
Prof. K. Adisesha
27
BufferedReader Class:
Java BufferedReader class is used to read the text from a character-based input stream.
It can be used to read data line by line by readLine() method.
➢ It makes the performance fast. It inherits Reader class.
package com.javatpoint;
import java.io.*;
public class BufferedReaderExample {
public static void main(String args[])throws Exception{
FileReader fr=new FileReader("D:f3.txt");
BufferedReader br=new BufferedReader(fr);
int i;
while((i=br.read())!=-1){ System.out.print((char)i); }
br.close();
fr.close();
} }
28. Java File Stream
Prof. K. Adisesha
28
Java Scanner:
Scanner class in Java is found in the java.util package. Java provides various ways to
read input from the keyboard, the java.util.Scanner class is one of them.
➢ The Java Scanner class breaks the input into tokens using a delimiter which is whitespace by
default. It provides many methods to read and parse various primitive values.
➢ Java Scanner where we are getting a single input from the user. Here, we are asking for a string
through in.nextLine() method.
import java.util.*;
public class ScannerExample {
public static void main(String args[]){
Scanner in = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = in.nextLine();
System.out.println("Name is: " + name);
in.close();
}
}