[go: up one dir, main page]

0% found this document useful (0 votes)
22 views39 pages

Unit 5

Uploaded by

Bindu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views39 pages

Unit 5

Uploaded by

Bindu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 39

UNIT-V

EVENT HANDALING:

An event listener in Java is designed to process some kind of event — it "listens" for an event,
such as a user's mouse click or a key press, and then it responds accordingly. An event listener
must be connected to an event object that defines the event.

For example, graphical components like a JButton or JTextField are known as event sources.
This means that they can generate events (called event objects), such as providing a JButton for a
user to click, or a JTextField in which a user can enter text. The event listener's job is to catch
those events and do something with them.

Note that event listeners are flexible in that a single listener can be registered to "listen" to
multiple types of events. This means that, for a similar set of components that perform the same
type of action, one event listener can handle all the events.

Java Event classes and Listener interfaces

Event Classes Listener Interfaces

ActionEvent ActionListener

MouseEvent MouseListener and MouseMotionListener

MouseWheelEvent MouseWheelListener

KeyEvent KeyListener

ItemEvent ItemListener

TextEvent TextListener

AdjustmentEvent AdjustmentListener

WindowEvent WindowListener

ComponentEvent ComponentListener

ContainerEvent ContainerListener

FocusEvent FocusListene
Steps to perform Event Handling

Following steps are required to perform event handling:

1. Register the component with the Listener

Registration Methods

For registering the component with the Listener, many classes provide the registration methods.
For example:

o Button
o public void addActionListener(ActionListener a){}
o MenuItem
o public void addActionListener(ActionListener a){}
o TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
o TextArea
o public void addTextListener(TextListener a){}
o Checkbox
o public void addItemListener(ItemListener a){}
o Choice
o public void addItemListener(ItemListener a){}
o List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}

Delegation Event Model in Java

The Delegation Event model is defined to handle events in GUI programming languages.
The GUI stands for Graphical User Interface, where a user graphically/visually interacts with the
system.

The GUI programming is inherently event-driven; whenever a user initiates an activity such as a
mouse activity, clicks, scrolling, etc., each is known as an event that is mapped to a code to
respond to functionality to the user. This is known as event handling.
In this section, we will discuss event processing and how to implement the delegation event
model in Java. We will also discuss the different components of an Event Model.

Event Processing in Java

Java support event processing since Java 1.0. It provides support for AWT ( Abstract Window
Toolkit), which is an API used to develop the Desktop application. In Java 1.0, the AWT was
based on inheritance. To catch and process GUI events for a program, it should hold subclass
GUI components and override action() or handleEvent() methods. The below image
demonstrates the event processing.

But, the modern approach for event processing is based on the Delegation Model. It defines a
standard and compatible mechanism to generate and process events. In this model, a source
generates an event and forwards it to one or more listeners. The listener waits until it receives an
event. Once it receives the event, it is processed by the listener and returns it. The UI elements
are able to delegate the processing of an event to a separate function.

The key advantage of the Delegation Event Model is that the application logic is completely
separated from the interface logic.

In the older model, an event was propagated up the containment until a component was handled.
This needed components to receive events that were not processed, and it took lots of time. The
Delegation Event model overcame this issue.

Basically, an Event Model is based on the following three components:

o Events
o Events Sources
o Events Listeners

Events

The Events are the objects that define state change in a source. An event can be generated as a
reaction of a user while interacting with GUI elements. Some of the event generation activities
are moving the mouse pointer, clicking on a button, pressing the keyboard key, selecting an item
from the list, and so on. We can also consider many other user operations as events.

The Events may also occur that may be not related to user interaction, such as a timer expires,
counter exceeded, system failures, or a task is completed, etc. We can define events for any of
the applied actions.

Event Sources

A source is an object that causes and generates an event. It generates an event when the internal
state of the object is changed. The sources are allowed to generate several different types of
events.

A source must register a listener to receive notifications for a specific event. Each event contains
its registration method. Below is an example:

1. public void addTypeListener (TypeListener e1)

From the above syntax, the Type is the name of the event, and e1 is a reference to the event
listener. For example, for a keyboard event listener, the method will be called
as addKeyListener(). For the mouse event listener, the method will be called
as addMouseMotionListener(). When an event is triggered using the respected source, all the
events will be notified to registered listeners and receive the event object. This process is known
as event multicasting. In few cases, the event notification will only be sent to listeners that
register to receive them.

Some listeners allow only one listener to register. Below is an example:

1. public void addTypeListener(TypeListener e2) throws java.util.TooManyListenersException

From the above syntax, the Type is the name of the event, and e2 is the event listener's reference.
When the specified event occurs, it will be notified to the registered listener. This process is
known as unicasting events.

A source should contain a method that unregisters a specific type of event from the listener if not
needed. Below is an example of the method that will remove the event from the listener.
1. public void removeTypeListener(TypeListener e2?)

From the above syntax, the Type is an event name, and e2 is the reference of the listener. For
example, to remove the keyboard listener, the removeKeyListener() method will be called.

The source provides the methods to add or remove listeners that generate the events. For
example, the Component class contains the methods to operate on the different types of events,
such as adding or removing them from the listener.

Event Listeners

An event listener is an object that is invoked when an event triggers. The listeners require two
things; first, it must be registered with a source; however, it can be registered with several
resources to receive notification about the events. Second, it must implement the methods to
receive and process the received notifications.

The methods that deal with the events are defined in a set of interfaces. These interfaces can be
found in the java.awt.event package.

For example, the MouseMotionListener interface provides two methods when the mouse is
dragged and moved. Any object can receive and process these events if it implements the
MouseMotionListener interface.

Types of Events

The events are categories into the following two categories:

The Foreground Events:

The foreground events are those events that require direct interaction of the user. These types of
events are generated as a result of user interaction with the GUI component. For example,
clicking on a button, mouse movement, pressing a keyboard key, selecting an option from the
list, etc.

The Background Events :

The Background events are those events that result from the interaction of the end-user. For
example, an Operating system interrupts system failure (Hardware or Software).

To handle these events, we need an event handling mechanism that provides control over the
events and responses.

The Delegation Model


The Delegation Model is available in Java since Java 1.1. it provides a new delegation-based
event model using AWT to resolve the event problems. It provides a convenient mechanism to
support complex Java programs.

Design Goals

The design goals of the event delegation model are as following:

o It is easy to learn and implement


o It supports a clean separation between application and GUI code.
o It provides robust event handling program code which is less error-prone (strong
compile-time checking)
o It is Flexible, can enable different types of application models for event flow and
propagation.
o It enables run-time discovery of both the component-generated events as well as
observable events.
o It provides support for the backward binary compatibility with the previous model.

Java Event Handling Code

We can put the event handling code into one of the following places:

1. Within class
2. Other class
3. Anonymous class

ActionListeners:

The Java ActionListener is notified whenever you click on the button or menu item. It is notified
against ActionEvent. The ActionListener interface is found in java.awt.event package. It has only
one method: actionPerformed().

actionPerformed() method

The actionPerformed() method is invoked automatically whenever you click on the registered
component.

1. public abstract void actionPerformed(ActionEvent e);


How to write ActionListener

The common approach is to implement the ActionListener. If you implement the ActionListener
class, you need to follow 3 steps:

1) Implement the ActionListener interface in the class:

1. public class ActionListenerExample Implements ActionListener

2) Register the component with the Listener:

1. component.addActionListener(instanceOfListenerclass);

3) Override the actionPerformed() method:

1. public void actionPerformed(ActionEvent e){


2. //Write the code here
3. }

Java ActionListener Example: On Button click

1. import java.awt.*;
2. import java.awt.event.*;
3. //1st step
4. public class ActionListenerExample implements ActionListener{
5. public static void main(String[] args) {
6. Frame f=new Frame("ActionListener Example");
7. final TextField tf=new TextField();
8. tf.setBounds(50,50, 150,20);
9. Button b=new Button("Click Here");
10. b.setBounds(50,100,60,30);
11. //2nd step
12. b.addActionListener(this);
13. f.add(b);f.add(tf);
14. f.setSize(400,400);
15. f.setLayout(null);
16. f.setVisible(true);
17. }
18. //3rd step
19. public void actionPerformed(ActionEvent e){
20. tf.setText("Welcome to Javatpoint.");
21. }
22. }

Output:

MouseListener:

The Java MouseListener is notified whenever you change the state of mouse. It is notified
against MouseEvent. The MouseListener interface is found in java.awt.event package. It has five
methods.

Methods of MouseListener interface

The signature of 5 methods found in MouseListener interface are given below:

1. mouseClicked(MouseEventev): This method will get invoked when a Mouse button is

clicked on a component.

2. mouseEntered(MouseEventev): This method will get invoked when a Mouse is entering a

component.
3. mouseExited(MouseEventev): This method will get invoked when a Mouse is exiting a

component.

4. mousePressed(MouseEventev): This method will get invoked when a Mouse button is

pressed on a component.

5. mouseReleased(MouseEventev): This method will get invoked when a Mouse button is


released on a component.

Java MouseListener Example

1. import java.awt.*;
2. import java.awt.event.*;
3. public class MouseListenerExample extends Frame implements MouseListener{
4. Label l;
5. MouseListenerExample(){
6. addMouseListener(this);
7.
8. l=new Label();
9. l.setBounds(20,50,100,20);
10. add(l);
11. setSize(300,300);
12. setLayout(null);
13. setVisible(true);
14. }
15. public void mouseClicked(MouseEvent e) {
16. l.setText("Mouse Clicked");
17. }
18. public void mouseEntered(MouseEvent e) {
19. l.setText("Mouse Entered");
20. }
21. public void mouseExited(MouseEvent e) {
22. l.setText("Mouse Exited");
23. }
24. public void mousePressed(MouseEvent e) {
25. l.setText("Mouse Pressed");
26. }
27. public void mouseReleased(MouseEvent e) {
28. l.setText("Mouse Released");
29. }
30. public static void main(String[] args) {
31. new MouseListenerExample();
32. }
33. }

Output:

Java MouseMotionListener Interface

The Java MouseMotionListener is notified whenever you move or drag mouse. It is notified
against MouseEvent. The MouseMotionListener interface is found in java.awt.event package. It
has two methods.

Methods of MouseMotionListener interface

The signature of 2 methods found in MouseMotionListener interface are given below:

1. public abstract void mouseDragged(MouseEvent e);


2. public abstract void mouseMoved(MouseEvent e);
Java MouseMotionListener Example

1. import java.awt.*;
2. import java.awt.event.*;
3. public class MouseMotionListenerExample extends Frame implements MouseMotionListener{

4. MouseMotionListenerExample(){
5. addMouseMotionListener(this);
6.
7. setSize(300,300);
8. setLayout(null);
9. setVisible(true);
10. }
11. public void mouseDragged(MouseEvent e) {
12. Graphics g=getGraphics();
13. g.setColor(Color.BLUE);
14. g.fillOval(e.getX(),e.getY(),20,20);
15. }
16. public void mouseMoved(MouseEvent e) {}
17.
18. public static void main(String[] args) {
19. new MouseMotionListenerExample();
20. }
21. }

Output:
Java KeyListener Interface

The Java KeyListener is notified whenever you change the state of key. It is notified against
KeyEvent. The KeyListener interface is found in java.awt.event package, and it has three
methods.

Interface declaration

Following is the declaration for java.awt.event.KeyListener interface:

1. public interface KeyListener extends EventListener

Methods of KeyListener interface

The signature of 3 methods found in KeyListener interface are given below:

Sr. no. Method name Description

1. public abstract void keyPressed (KeyEvent e); It is invoked when a key has been pressed.
2. public abstract void keyReleased (KeyEvent e); It is invoked when a key has been released.

3. public abstract void keyTyped (KeyEvent e); It is invoked when a key has been typed.

Methods inherited

This interface inherits methods from the following interface:

o java.awt.EventListener

Java KeyListener Example

In the following example, we are implementing the methods of the KeyListener interface.

KeyListenerExample.java

1. // importing awt libraries


2. import java.awt.*;
3. import java.awt.event.*;
4. // class which inherits Frame class and implements KeyListener interface
5. public class KeyListenerExample extends Frame implements KeyListener {
6. // creating object of Label class and TextArea class
7. Label l;
8. TextArea area;
9. // class constructor
10. KeyListenerExample() {
11. // creating the label
12. l = new Label();
13. // setting the location of the label in frame
14. l.setBounds (20, 50, 100, 20);
15. // creating the text area
16. area = new TextArea();
17. // setting the location of text area
18. area.setBounds (20, 80, 300, 300);
19. // adding the KeyListener to the text area
20. area.addKeyListener(this);
21. // adding the label and text area to the frame
22. add(l);
23. add(area);
24. // setting the size, layout and visibility of frame
25. setSize (400, 400);
26. setLayout (null);
27. setVisible (true);
28. }
29. // overriding the keyPressed() method of KeyListener interface where we set the text of the label
when key is pressed
30. public void keyPressed (KeyEvent e) {
31. l.setText ("Key Pressed");
32. }
33. // overriding the keyReleased() method of KeyListener interface where we set the text of the labe
l when key is released
34. public void keyReleased (KeyEvent e) {
35. l.setText ("Key Released");
36. }
37. // overriding the keyTyped() method of KeyListener interface where we set the text of the label
when a key is typed
38. public void keyTyped (KeyEvent e) {
39. l.setText ("Key Typed");
40. }
41. // main method
42. public static void main(String[] args) {
43. new KeyListenerExample();
44. }
45. }

Output:
Java WindowListener Interface

The Java WindowListener is notified whenever you change the state of window. It is notified
against WindowEvent. The WindowListener interface is found in java.awt.event package. It has
three methods.

WindowListener interface declaration

The declaration for java.awt.event.WindowListener interface is shown below:

1. public interface WindowListener extends EventListener

Methods of WindowListener interface

The signature of 7 methods found in WindowListener interface with their usage are given below:
Sr. Method signature Description
no.

1. public abstract void windowActivated It is called when the Window is set to be an active
(WindowEvent e); Window.

2. public abstract void windowClosed It is called when a window has been closed as the
(WindowEvent e); result of calling dispose on the window.

3. public abstract void windowClosing It is called when the user attempts to close the
(WindowEvent e); window from the system menu of the window.

4. public abstract void It is called when a Window is not an active Window


windowDeactivated (WindowEvent e); anymore.

5. public abstract void It is called when a window is changed from a


windowDeiconified (WindowEvent e); minimized to a normal state.

6. public abstract void windowIconified It is called when a window is changed from a


(WindowEvent e); normal to a minimized state.

7. public abstract void windowOpened It is called when window is made visible for the first
(WindowEvent e); time.

Methods inherited by the WindowListener

This interface inherits methods from the EventListener interface.

Working of WindowListener interface


o If a class needs to process some Window events, an object should exist which can
implement the interface.
o As the object is already registered with Listener, an event will be generated on all the
states of window.
o This helps in generation of invocation of relevant method in listener's object. And then
WindowEvent is passed after invocation.
Java WindowListener Example

In the following example, we are going to implement all the method of WindowListener
interface one by one.

WindowExample.java

1. // importing necessary libraries of awt


2. import java.awt.*;
3. import java.awt.event.WindowEvent;
4. import java.awt.event.WindowListener;
5.
6. // class which inherits Frame class and implements WindowListener interface
7. public class WindowExample extends Frame implements WindowListener {
8.
9. // class constructor
10. WindowExample() {
11.
12. // adding WindowListener to the frame
13. addWindowListener(this);
14. // setting the size, layout and visibility of frame
15. setSize (400, 400);
16. setLayout (null);
17. setVisible (true);
18. }
19. // main method
20. public static void main(String[] args) {
21. new WindowExample();
22. }
23.
24. // overriding windowActivated() method of WindowListener interface which prints the given stri
ng when window is set to be active
25. public void windowActivated (WindowEvent arg0) {
26. System.out.println("activated");
27. }
28.
29. // overriding windowClosed() method of WindowListener interface which prints the given string
when window is closed
30. public void windowClosed (WindowEvent arg0) {
31. System.out.println("closed");
32. }
33.
34. // overriding windowClosing() method of WindowListener interface which prints the given string
when we attempt to close window from system menu
35. public void windowClosing (WindowEvent arg0) {
36. System.out.println("closing");
37. dispose();
38. }
39.
40. // overriding windowDeactivated() method of WindowListener interface which prints the given s
tring when window is not active
41. public void windowDeactivated (WindowEvent arg0) {
42. System.out.println("deactivated");
43. }
44.
45. // overriding windowDeiconified() method of WindowListener interface which prints the given st
ring when window is modified from minimized to normal state
46. public void windowDeiconified (WindowEvent arg0) {
47. System.out.println("deiconified");
48. }
49.
50. // overriding windowIconified() method of WindowListener interface which prints the given strin
g when window is modified from normal to minimized state
51. public void windowIconified(WindowEvent arg0) {
52. System.out.println("iconified");
53. }
54.
55. // overriding windowOpened() method of WindowListener interface which prints the given string
when window is first opened
56. public void windowOpened(WindowEvent arg0) {
57. System.out.println("opened");
58. }
59. }

Output:
Java Adapter Classes

Java adapter classes provide the default implementation of listener interfaces. If you inherit the
adapter class, you will not be forced to provide the implementation of all the methods of listener
interfaces. So it saves code.

Pros of using Adapter classes:


o It assists the unrelated classes to work combinedly.
o It provides ways to use classes in different ways.
o It increases the transparency of classes.
o It provides a way to include related patterns in the class.
o It provides a pluggable kit for developing an application.
o It increases the reusability of the class.

The adapter classes are found in java.awt.event, java.awt.dnd and javax.swing.event packages.
The Adapter classes with their corresponding listener interfaces are given below.

java.awt.event Adapter classes

Adapter class Listener interface

WindowAdapter WindowListener

KeyAdapter KeyListener

MouseAdapter MouseListener

MouseMotionAdapter MouseMotionListener

FocusAdapter FocusListener

ComponentAdapter ComponentListener

ContainerAdapter ContainerListener
HierarchyBoundsAdapter HierarchyBoundsListener

java.awt.dnd Adapter classes

Adapter class Listener interface

DragSourceAdapter DragSourceListener

DragTargetAdapter DragTargetListener

javax.swing.event Adapter classes

Adapter class Listener interface

MouseInputAdapter MouseInputListener

InternalFrameAdapter InternalFrameListener

Java WindowAdapter Example

In the following example, we are implementing the WindowAdapter class of AWT and one its
methods windowClosing() to close the frame window.

AdapterExample.java

1. // importing the necessary libraries


2. import java.awt.*;
3. import java.awt.event.*;
4.
5. public class AdapterExample {
6. // object of Frame
7. Frame f;
8. // class constructor
9. AdapterExample() {
10. // creating a frame with the title
11. f = new Frame ("Window Adapter");
12. // adding the WindowListener to the frame
13. // overriding the windowClosing() method
14. f.addWindowListener (new WindowAdapter() {
15. public void windowClosing (WindowEvent e) {
16. f.dispose();
17. }
18. });
19. // setting the size, layout and
20. f.setSize (400, 400);
21. f.setLayout (null);
22. f.setVisible (true);
23. }
24.
25. // main method
26. public static void main(String[] args) {
27. new AdapterExample();
28. }
29. }

Output:

Java MouseAdapter Example


In the following example, we are implementing the MouseAdapter class. The MouseListener
interface is added into the frame to listen the mouse event in the frame.

MouseAdapterExample.java

1. // importing the necessary libraries


2. import java.awt.*;
3. import java.awt.event.*;
4.
5. // class which inherits the MouseAdapter class
6. public class MouseAdapterExample extends MouseAdapter {
7. // object of Frame class
8. Frame f;
9. // class constructor
10. MouseAdapterExample() {
11. // creating the frame with the title
12. f = new Frame ("Mouse Adapter");
13. // adding MouseListener to the Frame
14. f.addMouseListener(this);
15. // setting the size, layout and visibility of the frame
16. f.setSize (300, 300);
17. f.setLayout (null);
18. f.setVisible (true);
19. }
20. // overriding the mouseClicked() method of the MouseAdapter class
21. public void mouseClicked (MouseEvent e) {
22. // creating the Graphics object and fetching them from the Frame object using getGraphics() met
hod
23. Graphics g = f.getGraphics();
24. // setting the color of graphics object
25. g.setColor (Color.BLUE);
26. // setting the shape of graphics object
27. g.fillOval (e.getX(), e.getY(), 30, 30);
28. }
29. // main method
30. public static void main(String[] args) {
31. new MouseAdapterExample();
32. }
33. }

Output:

Applet in Java:

An applet is a special kind of Java program that runs in a Java enabled browser. This is the first
Java program that can run over the network using the browser. Applet is typically embedded
inside a web page and runs in the browser.

In other words, we can say that Applets are small Java applications that can be accessed on an
Internet server, transported over Internet, and can be automatically installed and run as apart of a
web document.

After a user receives an applet, the applet can produce a graphical user interface. It has limited
access to resources so that it can run complex computations without introducing the risk of
viruses or breaching data integrity.

To create an applet, a class must class extends java.applet.Applet class.

An Applet class does not have any main() method. It is viewed using JVM. The JVM can use
either a plug-in of the Web browser or a separate runtime environment to run an applet
application.
JVM creates an instance of the applet class and invokes init() method to initialize an Applet.

Note: Java Applet is deprecated since Java 9. It means Applet API is no longer considered
important.

Advantage of Applet

There are many advantages of applet. They are as follows:

o It works at client side so less response time.


o Secured
o It can be executed by browsers running under many plateforms, including Linux,
Windows, Mac Os etc.

Drawback of Applet
o Plugin is required at client browser to execute applet.

Hierarchy of Applet
As displayed in the above diagram, Applet class extends Panel. Panel class extends Container which is t
subclass of Component.

Lifecycle of Java Applet


1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.

Lifecycle methods for Applet:

The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides 1 life
cycle methods for an applet.

java.applet.Applet class

For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle
methods of applet.
1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized. It is used
to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or
browser is minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.

java.awt.Component class

The Component class provides 1 life cycle method of applet.

1. public void paint(Graphics g): is used to paint the Applet. It provides Graphics class
object that can be used for drawing oval, rectangle, arc etc.

Who is responsible to manage the life cycle of an applet?

Java Plug-in software.

How to run an Applet?

There are two ways to run an applet

1. By html file.
2. By appletViewer tool (for testing purpose).

Simple example of Applet by html file:

To execute the applet by html file, create an applet and compile it. After that create an html file
and place the applet code in html file. Now click the html file.

1. //First.java
2. import java.applet.Applet;
3. import java.awt.Graphics;
4. public class First extends Applet{
5.
6. public void paint(Graphics g){
7. g.drawString("welcome",150,150);
8. }
9.
10. }
Note: class must be public because its object is created by Java Plugin software that resides on
the browser.

myapplet.html
1. <html>
2. <body>
3. <applet code="First.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>

Simple example of Applet by appletviewer tool:

To execute the applet by appletviewer tool, create an applet that contains applet tag in comment
and compile it. After that run it by: appletviewer First.java. Now Html file is not required but it
is for testing purpose only.

1. //First.java
2. import java.applet.Applet;
3. import java.awt.Graphics;
4. public class First extends Applet{
5.
6. public void paint(Graphics g){
7. g.drawString("welcome to applet",150,150);
8. }
9.
10. }
11. /*
12. <applet code="First.class" width="300" height="300">
13. </applet>
14. */
To execute the applet by appletviewer tool, write in command prompt:

c:\>javac First.java
c:\>appletviewer First.java

Graphics in Applet

In Applet, java.awt.Graphicsclass provides methods for using graphics.

Below are the Methods of the Graphics class.

Sr
Methods Description
No.

1 public abstract void drawString(String str, int x, int y) Used to draw specified string.

Used to draw a rectangle of specified


2 public void drawRect(int x, int y, int width, int height)
width and height.

public abstract void fillRect(int x, int y, int width, int Used to draw a rectangle with a default
3
height) colourof specified width and height.

public abstract void drawOval(int x, int y, int width, int Used to draw oval of specified width and
4
height) height.

public abstract void fillOval(int x, int y, int width, int Used to draw oval with a default colour of
5
height) specified width and height.
public abstract void drawLine(int x1, int y1, int x2, int Used for drawing lines between the point
6
y2) (x1, x1) and (x2, y2).

public abstract booleandrawImage(Image img, int x, int


7 Used for drawing a specified image.
y, ImageObserver observer)

public abstract void drawArc(int x, int y, int width, int


8 Used for drawing a circular arc.
height, intstartAngle, intarcAngle)

public abstract void fillArc(int x, int y, int width, int


9 Used for filling circular arc.
height, intstartAngle, intarcAngle)

10 public abstract void setColor(Color c) Used to set a colour to the object.

11 public abstract void setFont(Font font) Used to set font.

Working with Images in Applet


In Applet programs, images also can be used

java.awt.Image class is used for representing an image.

java.applet, java.awt and java.awt.image are the packages which are used for event handling.
Loading an image

In Applet, images are loaded using getImage() method. This method works when the constructor
of the Applet is called. It is always suggested to call the constructor in init() method.

Here are some examples:

Image image1 = getImage(getCodeBase(), "image1.gif"); Image image2 =


getImage(getDocumentBase(), "image1.jpeg"); Image image3 = getImage(new
URL("http://java.sun.com/graphics/image.gif"));

Displaying an image

In Applet, images are displayed using drawImage() method. This method is supplied by the
Graphics object, which is passed to paint() method.

Example:

Aimage.java

import java.awt.*;

import java.applet.*;

public class Aimage extends Applet

Image img1;

public void init()

img1=getImage(getDocumentBase(),"icon.png");

}
public void paint(Graphics g)

g.drawImage(img1,100,100,this);

<html>

<applet code=Aimage height=300 width=300>

</applet>

</html>
EventHandling in Applet
In Applet we can also perform event handling.

Below is an example of event handling which prints a message when clicked on the button.

Example:

EventAppletDemo.java

import java.applet.*;

import java.awt.*;

import java.awt.event.*;

public class EventAppletDemo extends Applet implements ActionListener

Button b1;

TextField tf1;

public void init()

tf1=new TextField();

tf1.setBounds(30,40,200,20);

b1=new Button("Click");

b1.setBounds(80,150,60,50);

add(b1);

add(tf1);
b1.addActionListener(this);

setLayout(null);

public void actionPerformed(ActionEvent e)

tf1.setText("Welcome to studytonight");

Copy

Myapplet.html

<html>

<body>

<applet code="EventAppletDemo.class" width="300" height="300">

</applet>

</body>

</html>
Animation in Applet
In Applet, we can also create animations in a program using a gif image. Below is an example in
which drawImage() method is used which is of Graphics class, it is used for displaying an image.

Note: Download a gif file for the below example

Example:

AnimationDemo.java

import java.awt.*;

import java.applet.*;

public class AnimationDemo extends Applet

{
Image p;

public void init()

p = getImage(getDocumentBase(),"ball.gif");

public void paint(Graphics g)

for(inti=0;i<500;i++)

g.drawImage(p, i,50, this);

try

Thread.sleep(100);

catch(Exception e)

{}
Difference between a Java Application and a Java Applet

Java Application is just like a Java program that runs on an underlying operating system with
the support of a virtual machine. It is also known as an application program. The graphical user
interface is not necessary to execute the java applications, it can be run with or without it.
Java Applet is an applet is a Java program that can be embedded into a web page. It runs
inside the web browser and works on the client-side. An applet is embedded in an HTML
page using the APPLET or OBJECT tag and hosted on a web server. Applets are used to
make the website more dynamic and entertaining.
The difference between Application and Applet:

Parameters Java Application Java Applet

Applications are just like a Java Applets are small Java programs that are
program that can be executed designed to be included with the HTML
independently without using the web document. They require a Java-
Definition web browser. enabled web browser for execution.

The applet does not require the main()


main () The application program requires method for its execution instead init()
method a main() method for its execution. method is required.

The “javac” command is used to Applet programs are compiled with the
compile application programs, “javac” command and run using either
which are then executed using the the “appletviewer” command or the web
Compilation “java” command. browser.

Java application programs have


full access to the local file system Applets don’t have local disk and
File access and network. network access.
Parameters Java Application Java Applet

Applications can access all kinds Applets can only access browser-specific
of resources available on the services. They don’t have access to the
Access level system. local system.

First and foremost, the


installation of a Java application
on the local computer is The Java applet does not need to be
Installation required. installed beforehand.

Applications can execute the Applets cannot execute programs from


Execution programs from the local system. the local machine.

An application program is needed


to perform some tasks directly for An applet program is needed to perform
Program the user. small tasks or part of them.

It cannot start on its own, but it can be


It cannot run on its own; it needs executed using a Java-enabled web
Run JRE to execute. browser.

Connection Connectivity with other servers is


with servers possible. It is unable to connect to other servers.

Read and It supports the reading and


Write writing of files on the local It does not support the reading and
Operation computer. writing of files on the local computer.

Executed in a more restricted


Application can access the environment with tighter security. They
system’s data and resources can only use services that are exclusive to
Security without any security limitations. their browser.

Java applications are self-


contained and require no Applet programs cannot run on their own,
additional security because they necessitating the maximum level of
Restrictions are trusted. security.
Security Issues with the Applet
Java applet is run inside a web browser. But an applet is restricted in some areas, until it has been
deemed trustworthy by the end user. The security restriction is provided for protecting the user
by malicious code, like copy important information from the hard disk or deleting the files.
Generally, applets are loaded from the Internet and they are prevented from: the writing and
reading the files on client side. Some security issues to applet are following :

 Applets are loaded over the internet and they are prevented to make open network
connection to any computer, except for the host, which provided the .class file. Because
the html page come from the host or the host specified codebase parameter in the applet
tag, with codebase taking precedence.

 They are also prevented from starting other programs on the client. That means any
applet, which you visited, cannot start any rogue process on you computer. In UNIX,
applets cannot start any exec or fork processes. Applets are not allowed to invoke any
program to list the contents of your file system that means it cant
invoke System.exit() function to terminate you web browser. And they are not allowed to
manipulate the threads outside the applets own thread group.

 Applets are loaded over the net. A web browser uses only one class loader that?s
established at start up. Then the system class loader can not be overloaded, overridden,
extended, replaced. Applet is not allowed to create the reference of their own class
loader.

 They cant load the libraries or define the native method calls. But if it can define native
method calls then that would give the applet direct access to underlying computer.

You might also like