KEMBAR78
Class notes(week 10) on applet programming | PDF
Page 1 of 13
Class Notes on Applet Programming (using swing) (Week - 10)
Contents: - Basics of applet programming, applet life cycle, difference between application & applet programming,
parameter passing in applet in applets, concept of delegation event model and listener, I/O in applets, use of repaint(),
getDocumentBase(), getCodeBase() methods, layout manager (basic concept), creation of buttons (JButton class only) &
text fields.
Java applet
A Java applet is a small application written in Java, and delivered to users in the form of bytecode. The user launches the
Java applet from a web page. The Java applet then executes within a Java Virtual Machine (JVM) in a process separate
from the web browser itself, yet it can appear in a frame of the web page, in a new application window, or in Sun's
AppletViewer, a stand-alone tool for testing applets. Java applets were introduced in the first version of the Java
language in 1995.
What is an applet?
Applets are small applications that are accessed on an Internet server, transported over the Internet, automatically
installed, and run as part of a Web document. After an applet arrives on the client, it has limited access to resources, so
that it can produce an arbitrary multimedia user interface and run complex computations without introducing the risk of
viruses or breaching data integrity.
The simple applet
import java.awt.*;
import java.applet.*;
public class SimpleApplet extends Applet {
public void paint(Graphics g) {
g.drawString("A Simple Applet", 20, 20);
}
}
This applet begins with two import statements.
 The first imports the Abstract Window Toolkit (AWT) classes. Applets interact with the user through the AWT,
not through the console-based I/O classes. The AWT contains support for a window-based, graphical interface.
As you might expect, the AWT is quite large and sophisticated, and a complete discussion of it is out of the scope
of this note. Fortunately, this simple applet makes very limited use of the AWT.
Page 2 of 13
 The second import statement imports the applet package, which contains the class Applet. Every applet that you
create must be a subclass of Applet.
The next line in the program declares the class SimpleApplet.
NOTE:-This class must be declared as public, because it will be accessed by code that is outside the program.
Inside SimpleApplet, paint( ) is declared. This method is defined by the AWT and must be overridden by the applet.
paint( ) is called each time that the applet must redisplay its output. This situation can occur for several reasons. For
example, the window in which the applet is running can be overwritten by another window and then uncovered. Or, the
applet window can be minimized and then restored, paint( ) is also called when the applet begins execution. Whatever
the cause, whenever the applet must redraw its output, paint( ) is called. The paint( ) method has one parameter of type
Graphics. This parameter contains the graphics context, which describes the graphics environment in which the applet is
running. This context is used whenever output to the applet is required.
Inside paint( ) is a call to drawString( ), which is a member of the Graphics class. This method outputs a string
beginning at the specified X,Y location. It has the following general form:
void drawString(String message, int x, int y);
The co-ordinates system of computer graphics is shown below for your reference
Here, message is the string to be output beginning at x,y. In a Java window, the upper-left corner is location 0,0. The call
to drawString( ) in the applet causes the message “A Simple Applet” to be displayed beginning at location 20,20.
Notice that the applet does not have a main( ) method. Unlike Java programs, applets do not begin execution at
main(). In fact, most applets don’t even have a main( ) method. Instead, an applet begins execution when the name of
its class is passed to an applet viewer or to an Internet browser.
After you enter the source code for SimpleApplet, compile in the same way that you have been compiling programs.
However, running SimpleApplet involves a different process. In fact, there are two ways in which you can run an applet:
Executing the applet within a Java-compatible Web browser.
Using an applet viewer, such as the standard SDK tool, appletviewer. An applet viewer executes your applet in a
window. This is generally the fastest and easiest way to test your applet.
Page 3 of 13
Each of these methods is described next.
To execute an applet in a Web browser, you need to write a short HTML text file that contains the appropriate APPLET
tag. Here is the HTML file that executes
SimpleApplet:
<applet code="SimpleApplet" width=200 height=60>
</applet>
The width and height statements specify the dimensions of the display area used by the applet. (The APPLET tag
contains several other options that are examined more closely later is this note.) After you create this file, you can
execute your browser and then load this file, which causes SimpleApplet to be executed.
To execute SimpleApplet with an applet viewer, you may also execute the HTML file shown earlier. For example,
if the preceding HTML file is called RunApp.html, then the following command line will run SimpleApplet:
C:>appletviewer RunApp.html
However, a more convenient method exists that you can use to speed up testing. Simply include a comment at the head
of your Java source code file that contains the APPLET tag. By doing so, your code is documented with a prototype of the
necessary HTML statements, and you can test your compiled applet merely by starting the appletviewer with your Java
source code file. If you use this method, the SimpleApplet source file looks like this:
import java.awt.*;
import java.applet.*;
/*
<applet code="SimpleApplet" width=200 height=60>
</applet>
*/
public class SimpleApplet extends Applet {
public void paint(Graphics g) {
g.drawString("A Simple Applet", 20, 20);
}
}
In general, you can quickly iterate through applet development by using these three steps:
 Edit a Java source file.
 Compile your program.
 Execute the applet viewer, specifying the name of your applet’s source file. The applet viewer will encounter the
APPLET tag within the comment and execute your applet.
C:>appletviewer SimpleApplet.java
The window produced by SimpleApplet, as displayed by the applet viewer, is shown in the following illustration:
Page 4 of 13
Here are the key points that you should remember now:
 Applets do not need a main( ) method.
 Applets must be run under an applet viewer or a Java-compatible browser.
 User I/O is not accomplished with Java’s stream I/O classes. Instead, applets use the interface provided by the
AWT.
The complete syntax of the <applet>tag is as follows:
Page 5 of 13
Viewing Applets from a Web Browser
To make your applet accessible on the Web, you need to store the class file (say SampleApplet.class) and HTML
webpage (say DisplayApplet.html) on a Web server. You can view the applet from an appropriate URL.
Page 6 of 13
Page 7 of 13
Applications Vs. Applets
Feature Application Applet
main()
method
Present Not present
Execution Requires JRE Requires a browser like Chrome
Nature Called as stand-alone application as application can be
executed from command prompt
Requires some third party tool help like a
browser to execute
Restrictions Can access any data or software available on the system cannot access any thing on the system
except browser’s services
Security Does not require any security Requires highest security for the system as
they are untrusted
Advantages of Applets
1. Execution of applets is easy in a Web browser and does not require any installation or deployment procedure in
realtime programming (where as servlets require).
2. Writing and displaying (just opening in a browser) graphics and animations is easier than applications.
Page 8 of 13
3. In GUI development, constructor, size of frame, window closing code etc. are not required (but are required in
applications).
Restrictions of Applets
1. Applets are required separate compilation before opening in a browser.
2. In realtime environment, the bytecode of applet is to be downloaded from the server to the client machine.
3. Applets are treated as untrusted (as they were developed by unknown people and placed on unknown servers
whose trustworthiness is not guaranteed) and for this reason they are not allowed, as a security measure, to
access any system resources like file system etc. available on the client system.
4. Extra Code is required to communicate between applets using AppletContext.
What Applet can't do – Security Limitations
Applets are treated as untrusted because they are developed by somebody and placed on some unknown Web server.
When downloaded, they may harm the system resources or steal passwords and valuable information available on the
system. As applets are untrusted, the browsers come with many security restrictions. Security policies are browser
dependent. Browser does not allow the applet to access any of the system resources (applet is permitted to use browser
resources, infact, applet execution goes within the browser only).
 Applets are not permitted to use any system resources like file system as they are untrusted and can inject virus
into the system.
 Applets cannot read from or write to hard disk files.
 Applet methods cannot be native.
 Applets should not attempt to create socket connections
 Applets cannot read system properties
 Applets cannot use any software available on the system (except browser execution area)
 Cannot create objects of applications available on the system by composition
The JRE throws SecurityException if the applet violates the browser restrictions.
What is delegation event model in java?
Event model is based on the concept of an 'Event Source' and 'Event Listeners'. Any object that is interested in receiving
messages (or events ) is called an Event Listener. Any object that generates these messages ( or events ) is called an
Event Source
Event Delegation Model is based on four concepts:
 The Event Classes
 The Event Listeners
 Explicit Event Enabling
 Adapters
The modern approach to handling events is based on the delegation event model, which defines standard and consistent
mechanisms to generate and process events. Its concept is quite simple: a source generates an event and sends it to one
or more listeners. In this scheme, the listener simply waits until it receives an event. Once received, the listener
processes the event and then returns. The advantage of this design is that the application logic that processes events is
cleanly separated from the user interface logic that generates those events. A user interface element is able to
"delegate"
the processing of an event to a separate piece of code.
Page 9 of 13
Overview of the Delegation Event Model
 The 1.1 event model is also called the "delegation" event model because event handling is delegated to different
objects and methods rather than having your Applet handle all the events.
 The idea is that events are processed by event listeners, which are separate objects that handle specific types of
events.
Note: In order to use the delegation event model properly, the Applet should not be the listener.
 The listener registers and specifies which events are of interest (for instance mouse events).
 Only those events that are being listened for will be processed.
 Each different event type uses a separate Event class.
 Each different kind of listener also uses a separate class.
 This model makes event handling more efficient because not all events have to be processed and the events
that are processed are only sent to the registered listeners rather than to an entire hierarchy of event handlers.
 This model also allows your Applet to be organized such that the application code and the interface code (the
GUI) can be separated.
 Also, using different event classes allows the Java compiler to perform more specific type error checking.
Event Listeners
An Event Listener, once set to an applet object waits for some action to be performed on it, be it mouse click, mouse
hover, pressing of keys, click of button, etc. The class you are using (e.g. JButton, etc.) reports the activity to a class set
by the class using it. That method then decides on how to react because of that action, usually with a series of if
statements to determine which action it was performed on. source.getSource() will return the name of the object
that the event was performed on, while the source is the object passed to the function when the action is performed.
Every single time the action is performed, it calls the method.
ActionListener
ActionListener is an interface that could be implemented in order to determine how certain event should be
handled. When implementing an interface, all methods in that interface should be implemented, ActionListener
interface has one method to implement named actionPerformed().
The following example shows how to implement ActionListener:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class ActionDemo extends JFrame implements ActionListener {
public ActionDemo() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(300, 300);
getContentPane().setLayout(new FlowLayout());
JButton b = new JButton("Click me");
getContentPane().add(b);
b.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(this, "Hi !!!");
}
Page 10 of 13
public static void main(String[] args) {
new ActionDemo().setVisible(true);
}
}
When you compile and run the above code, a message will appear when you click on the button.
The repaint() method-The GUI (AWT) Thread
One of a number of system threads. This thread is responsible for accepting input events and calling the paint() method.
The programmer should leave calling paint() to this thread. Java applets rarely call paint() directly.
There are two ways paint() calls are generated:
1. spontaneous painting, initiated by the environment
2. programmer generated calls via repaint() and update()
Spontaneous calls
In the first case, spontaneous painting refers to calls to paint() from the browser.
The GUI thread makes these calls. Every applet or application with a GUI (i.e., a Frame) has a GUI thread.
There are four situations when the GUI thread calls paint() spontaneously.
1. a window is covered by another and then re-exposed. Paint() is called to reconstruct the damaged parts of the
uncovered window
2. after deiconification
3. in an applet after init() has finished
4. when a browser returns to a page which contains an applet, provided the applet is at least partially exposed.
The repaint() Method
The second case, when paint() calls are genereted is when the program calls repaint() or update(). The repaint() method
is the one invoked by a program to do drawing. Their are 4 versions of this method but the one with no arguments is
usually used. Drawing via repaint() most often takes place in response to user input.
repaint() ==> update() ==(usually calls)==> paint()
repaint() does not invoke paint() directly. It schedules a call to an intermediate method, update(). Finally, update() calls
paint() (unless you override update).
Page 11 of 13
The reason for this complexity is Java's support for concurrent programming. It does this using threads.
Using repaint() can be tricky for at least three reasons.
1. the interaction between repaint() and the spontaneous painting done by the GUI thread
2. the fact that repaint() just asks the thread system to schedule a call to update()/paint() and then exits. The
repaint() method is asynchronous.
3. the problem of preventing your drawing from being erased when being updated.
All these potential complications are considered in details below.
However, let's start with a discussion what happens if paint() or update() are called directly.
Using paint( ) and update() directly.
What is of concern here is what happens if the user, for example, covers all or part of your drawing by another window,
and then uncovers your drawing again. Does it survive? Similarly, what happens if the user resizes the browser window?
When paint() is called after init(), or after the applet has been covered or iconified, it uses the default paint() which just
paints the background color, thereby erasing the image. A paint() method has been added. This works but the method
paint() is overly complex.
This is a simpler way to do it, because update() automatically covers the drawing area with the background colour,
essentially an erasing operation, and then automatically calls paint().
Preventing erasing by update()
Why calling paint() or update() directly is not such a good idea
The paint() method is always called by the AWT main GUI thread. It is possible that other applets are also using that
thread. The environment also uses the thread to reconstruct components damaged by, for example, resizing or
overlaying or iconifying/ deiconifying. If you have a complex paint() method and call it directly you may tie everything
else up, thereby degrading performance and defeating the multitasking nature of Java. A bug in your code may not only
stop you applet but everything else running on the page as well.
Using update() directly creates the same problems.
The repaint() method is designed to avoid these problems. However it can be tricky to use as it was mentioned before
The behaviour of repaint()
The behaviour of the following example is slightly different from the previous examples, if you only consider the applet
in isolation. In particular, it implements the different interface: MouseMotionListener interface. But the main difference
is that this version is more 'polite' than the others: it uses repaint.
If repaint() is just called by user interactions with components you should have no problems using repaint() this way.
However, if repaint() is called in a tight loop, the AWT thread queue may be overwhelmed and strange things may
happen.
Page 12 of 13
repaint() merely requests the AWT thread to call update(). It then returns immediately. This type of behaviour
is called asynchronous. How the AWT thread reacts to the request is up to it. This behavour can lead to
problems if you are not careful:
Multiple repaint() requests can unintentionally be combined into one
The behavour which causes the most trouble is the fact that the AWT may combine multiple rapid fire repaint()
requests into one request. In practice this behaviour often means that only the last repaint() request in the sequence
actually causes update() and paint() to be called. The result is that part of your beautiful drawing goes missing.
This problem usually occurs when repaint() is being called from a program loop.
Using Thread.sleep() to slow down repaint() requests
On the other hand, some textbooks recommend that you use the Thread.sleep() method. The idea is to put,
try {
Thread.sleep(100);
}
catch(InterruptedException ex) {}
either just before or just after the repaint() call. The Thread.sleep(100) puts the currently running thread to sleep for
100 milliseconds. This allows other threads, if there are any, a chance to run.
When only the AWT thread is present
This doesn't work! Putting the AWT thread to sleep solves nothing. Nothing happens, it wakes up, another repaint()
request comes in but the AWT thread goes to sleep again. So the pile up of requests just gets frozen for the sleep time.
In the end they are combined the same way as without the sleep and your drawing is still ruined.
In a multithreaded program
Using Thread.sleep() in a programmer created thread to slow down rapid fire repaint() calls solves the problem of
combined repaint() requests. The AWT GUI thread keeps running and has time to deal with requests to update() and
paint() because the thread which is the source of the requests is put to sleep periodically and thus slowed down. The
AWT thread meanwhile goes on its merry way.
getDocumentBase
public URL getDocumentBase()
Gets the URL of the document in which this applet is embedded. For example, suppose an applet is contained
within the document:
http://java.sun.com/products/jdk/1.2/index.html
The document base is:
http://java.sun.com/products/jdk/1.2/index.html
Returns: the URL of the document that contains this applet.
Page 13 of 13
getCodeBase
public URL getCodeBase()
Gets the base URL. This is the URL of the directory which contains this applet.
Returns:
the base URL of the directory which contains this applet.
Code for An applet program to give demo of getDocumentBase() and getCodeBase() methods in
Java
/* <applet code="URLDemo" height=100 width=400> </applet> */
import java.awt.*;
import java.applet.*;
import java.net.*;
publicclass URLDemo extends Applet
{
publicvoid paint(Graphics g){
String msg;
URL url=getCodeBase();
msg = "Code Base : "+url.toString();
g.drawString(msg,10,20);
url=getDocumentBase();
msg="Document Base : "+url.toString();
g.drawString(msg,10,40);
}
}

Class notes(week 10) on applet programming

  • 1.
    Page 1 of13 Class Notes on Applet Programming (using swing) (Week - 10) Contents: - Basics of applet programming, applet life cycle, difference between application & applet programming, parameter passing in applet in applets, concept of delegation event model and listener, I/O in applets, use of repaint(), getDocumentBase(), getCodeBase() methods, layout manager (basic concept), creation of buttons (JButton class only) & text fields. Java applet A Java applet is a small application written in Java, and delivered to users in the form of bytecode. The user launches the Java applet from a web page. The Java applet then executes within a Java Virtual Machine (JVM) in a process separate from the web browser itself, yet it can appear in a frame of the web page, in a new application window, or in Sun's AppletViewer, a stand-alone tool for testing applets. Java applets were introduced in the first version of the Java language in 1995. What is an applet? Applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part of a Web document. After an applet arrives on the client, it has limited access to resources, so that it can produce an arbitrary multimedia user interface and run complex computations without introducing the risk of viruses or breaching data integrity. The simple applet import java.awt.*; import java.applet.*; public class SimpleApplet extends Applet { public void paint(Graphics g) { g.drawString("A Simple Applet", 20, 20); } } This applet begins with two import statements.  The first imports the Abstract Window Toolkit (AWT) classes. Applets interact with the user through the AWT, not through the console-based I/O classes. The AWT contains support for a window-based, graphical interface. As you might expect, the AWT is quite large and sophisticated, and a complete discussion of it is out of the scope of this note. Fortunately, this simple applet makes very limited use of the AWT.
  • 2.
    Page 2 of13  The second import statement imports the applet package, which contains the class Applet. Every applet that you create must be a subclass of Applet. The next line in the program declares the class SimpleApplet. NOTE:-This class must be declared as public, because it will be accessed by code that is outside the program. Inside SimpleApplet, paint( ) is declared. This method is defined by the AWT and must be overridden by the applet. paint( ) is called each time that the applet must redisplay its output. This situation can occur for several reasons. For example, the window in which the applet is running can be overwritten by another window and then uncovered. Or, the applet window can be minimized and then restored, paint( ) is also called when the applet begins execution. Whatever the cause, whenever the applet must redraw its output, paint( ) is called. The paint( ) method has one parameter of type Graphics. This parameter contains the graphics context, which describes the graphics environment in which the applet is running. This context is used whenever output to the applet is required. Inside paint( ) is a call to drawString( ), which is a member of the Graphics class. This method outputs a string beginning at the specified X,Y location. It has the following general form: void drawString(String message, int x, int y); The co-ordinates system of computer graphics is shown below for your reference Here, message is the string to be output beginning at x,y. In a Java window, the upper-left corner is location 0,0. The call to drawString( ) in the applet causes the message “A Simple Applet” to be displayed beginning at location 20,20. Notice that the applet does not have a main( ) method. Unlike Java programs, applets do not begin execution at main(). In fact, most applets don’t even have a main( ) method. Instead, an applet begins execution when the name of its class is passed to an applet viewer or to an Internet browser. After you enter the source code for SimpleApplet, compile in the same way that you have been compiling programs. However, running SimpleApplet involves a different process. In fact, there are two ways in which you can run an applet: Executing the applet within a Java-compatible Web browser. Using an applet viewer, such as the standard SDK tool, appletviewer. An applet viewer executes your applet in a window. This is generally the fastest and easiest way to test your applet.
  • 3.
    Page 3 of13 Each of these methods is described next. To execute an applet in a Web browser, you need to write a short HTML text file that contains the appropriate APPLET tag. Here is the HTML file that executes SimpleApplet: <applet code="SimpleApplet" width=200 height=60> </applet> The width and height statements specify the dimensions of the display area used by the applet. (The APPLET tag contains several other options that are examined more closely later is this note.) After you create this file, you can execute your browser and then load this file, which causes SimpleApplet to be executed. To execute SimpleApplet with an applet viewer, you may also execute the HTML file shown earlier. For example, if the preceding HTML file is called RunApp.html, then the following command line will run SimpleApplet: C:>appletviewer RunApp.html However, a more convenient method exists that you can use to speed up testing. Simply include a comment at the head of your Java source code file that contains the APPLET tag. By doing so, your code is documented with a prototype of the necessary HTML statements, and you can test your compiled applet merely by starting the appletviewer with your Java source code file. If you use this method, the SimpleApplet source file looks like this: import java.awt.*; import java.applet.*; /* <applet code="SimpleApplet" width=200 height=60> </applet> */ public class SimpleApplet extends Applet { public void paint(Graphics g) { g.drawString("A Simple Applet", 20, 20); } } In general, you can quickly iterate through applet development by using these three steps:  Edit a Java source file.  Compile your program.  Execute the applet viewer, specifying the name of your applet’s source file. The applet viewer will encounter the APPLET tag within the comment and execute your applet. C:>appletviewer SimpleApplet.java The window produced by SimpleApplet, as displayed by the applet viewer, is shown in the following illustration:
  • 4.
    Page 4 of13 Here are the key points that you should remember now:  Applets do not need a main( ) method.  Applets must be run under an applet viewer or a Java-compatible browser.  User I/O is not accomplished with Java’s stream I/O classes. Instead, applets use the interface provided by the AWT. The complete syntax of the <applet>tag is as follows:
  • 5.
    Page 5 of13 Viewing Applets from a Web Browser To make your applet accessible on the Web, you need to store the class file (say SampleApplet.class) and HTML webpage (say DisplayApplet.html) on a Web server. You can view the applet from an appropriate URL.
  • 6.
  • 7.
    Page 7 of13 Applications Vs. Applets Feature Application Applet main() method Present Not present Execution Requires JRE Requires a browser like Chrome Nature Called as stand-alone application as application can be executed from command prompt Requires some third party tool help like a browser to execute Restrictions Can access any data or software available on the system cannot access any thing on the system except browser’s services Security Does not require any security Requires highest security for the system as they are untrusted Advantages of Applets 1. Execution of applets is easy in a Web browser and does not require any installation or deployment procedure in realtime programming (where as servlets require). 2. Writing and displaying (just opening in a browser) graphics and animations is easier than applications.
  • 8.
    Page 8 of13 3. In GUI development, constructor, size of frame, window closing code etc. are not required (but are required in applications). Restrictions of Applets 1. Applets are required separate compilation before opening in a browser. 2. In realtime environment, the bytecode of applet is to be downloaded from the server to the client machine. 3. Applets are treated as untrusted (as they were developed by unknown people and placed on unknown servers whose trustworthiness is not guaranteed) and for this reason they are not allowed, as a security measure, to access any system resources like file system etc. available on the client system. 4. Extra Code is required to communicate between applets using AppletContext. What Applet can't do – Security Limitations Applets are treated as untrusted because they are developed by somebody and placed on some unknown Web server. When downloaded, they may harm the system resources or steal passwords and valuable information available on the system. As applets are untrusted, the browsers come with many security restrictions. Security policies are browser dependent. Browser does not allow the applet to access any of the system resources (applet is permitted to use browser resources, infact, applet execution goes within the browser only).  Applets are not permitted to use any system resources like file system as they are untrusted and can inject virus into the system.  Applets cannot read from or write to hard disk files.  Applet methods cannot be native.  Applets should not attempt to create socket connections  Applets cannot read system properties  Applets cannot use any software available on the system (except browser execution area)  Cannot create objects of applications available on the system by composition The JRE throws SecurityException if the applet violates the browser restrictions. What is delegation event model in java? Event model is based on the concept of an 'Event Source' and 'Event Listeners'. Any object that is interested in receiving messages (or events ) is called an Event Listener. Any object that generates these messages ( or events ) is called an Event Source Event Delegation Model is based on four concepts:  The Event Classes  The Event Listeners  Explicit Event Enabling  Adapters The modern approach to handling events is based on the delegation event model, which defines standard and consistent mechanisms to generate and process events. Its concept is quite simple: a source generates an event and sends it to one or more listeners. In this scheme, the listener simply waits until it receives an event. Once received, the listener processes the event and then returns. The advantage of this design is that the application logic that processes events is cleanly separated from the user interface logic that generates those events. A user interface element is able to "delegate" the processing of an event to a separate piece of code.
  • 9.
    Page 9 of13 Overview of the Delegation Event Model  The 1.1 event model is also called the "delegation" event model because event handling is delegated to different objects and methods rather than having your Applet handle all the events.  The idea is that events are processed by event listeners, which are separate objects that handle specific types of events. Note: In order to use the delegation event model properly, the Applet should not be the listener.  The listener registers and specifies which events are of interest (for instance mouse events).  Only those events that are being listened for will be processed.  Each different event type uses a separate Event class.  Each different kind of listener also uses a separate class.  This model makes event handling more efficient because not all events have to be processed and the events that are processed are only sent to the registered listeners rather than to an entire hierarchy of event handlers.  This model also allows your Applet to be organized such that the application code and the interface code (the GUI) can be separated.  Also, using different event classes allows the Java compiler to perform more specific type error checking. Event Listeners An Event Listener, once set to an applet object waits for some action to be performed on it, be it mouse click, mouse hover, pressing of keys, click of button, etc. The class you are using (e.g. JButton, etc.) reports the activity to a class set by the class using it. That method then decides on how to react because of that action, usually with a series of if statements to determine which action it was performed on. source.getSource() will return the name of the object that the event was performed on, while the source is the object passed to the function when the action is performed. Every single time the action is performed, it calls the method. ActionListener ActionListener is an interface that could be implemented in order to determine how certain event should be handled. When implementing an interface, all methods in that interface should be implemented, ActionListener interface has one method to implement named actionPerformed(). The following example shows how to implement ActionListener: import javax.swing.*; import java.awt.*; import java.awt.event.*; class ActionDemo extends JFrame implements ActionListener { public ActionDemo() { setDefaultCloseOperation(EXIT_ON_CLOSE); setSize(300, 300); getContentPane().setLayout(new FlowLayout()); JButton b = new JButton("Click me"); getContentPane().add(b); b.addActionListener(this); } public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(this, "Hi !!!"); }
  • 10.
    Page 10 of13 public static void main(String[] args) { new ActionDemo().setVisible(true); } } When you compile and run the above code, a message will appear when you click on the button. The repaint() method-The GUI (AWT) Thread One of a number of system threads. This thread is responsible for accepting input events and calling the paint() method. The programmer should leave calling paint() to this thread. Java applets rarely call paint() directly. There are two ways paint() calls are generated: 1. spontaneous painting, initiated by the environment 2. programmer generated calls via repaint() and update() Spontaneous calls In the first case, spontaneous painting refers to calls to paint() from the browser. The GUI thread makes these calls. Every applet or application with a GUI (i.e., a Frame) has a GUI thread. There are four situations when the GUI thread calls paint() spontaneously. 1. a window is covered by another and then re-exposed. Paint() is called to reconstruct the damaged parts of the uncovered window 2. after deiconification 3. in an applet after init() has finished 4. when a browser returns to a page which contains an applet, provided the applet is at least partially exposed. The repaint() Method The second case, when paint() calls are genereted is when the program calls repaint() or update(). The repaint() method is the one invoked by a program to do drawing. Their are 4 versions of this method but the one with no arguments is usually used. Drawing via repaint() most often takes place in response to user input. repaint() ==> update() ==(usually calls)==> paint() repaint() does not invoke paint() directly. It schedules a call to an intermediate method, update(). Finally, update() calls paint() (unless you override update).
  • 11.
    Page 11 of13 The reason for this complexity is Java's support for concurrent programming. It does this using threads. Using repaint() can be tricky for at least three reasons. 1. the interaction between repaint() and the spontaneous painting done by the GUI thread 2. the fact that repaint() just asks the thread system to schedule a call to update()/paint() and then exits. The repaint() method is asynchronous. 3. the problem of preventing your drawing from being erased when being updated. All these potential complications are considered in details below. However, let's start with a discussion what happens if paint() or update() are called directly. Using paint( ) and update() directly. What is of concern here is what happens if the user, for example, covers all or part of your drawing by another window, and then uncovers your drawing again. Does it survive? Similarly, what happens if the user resizes the browser window? When paint() is called after init(), or after the applet has been covered or iconified, it uses the default paint() which just paints the background color, thereby erasing the image. A paint() method has been added. This works but the method paint() is overly complex. This is a simpler way to do it, because update() automatically covers the drawing area with the background colour, essentially an erasing operation, and then automatically calls paint(). Preventing erasing by update() Why calling paint() or update() directly is not such a good idea The paint() method is always called by the AWT main GUI thread. It is possible that other applets are also using that thread. The environment also uses the thread to reconstruct components damaged by, for example, resizing or overlaying or iconifying/ deiconifying. If you have a complex paint() method and call it directly you may tie everything else up, thereby degrading performance and defeating the multitasking nature of Java. A bug in your code may not only stop you applet but everything else running on the page as well. Using update() directly creates the same problems. The repaint() method is designed to avoid these problems. However it can be tricky to use as it was mentioned before The behaviour of repaint() The behaviour of the following example is slightly different from the previous examples, if you only consider the applet in isolation. In particular, it implements the different interface: MouseMotionListener interface. But the main difference is that this version is more 'polite' than the others: it uses repaint. If repaint() is just called by user interactions with components you should have no problems using repaint() this way. However, if repaint() is called in a tight loop, the AWT thread queue may be overwhelmed and strange things may happen.
  • 12.
    Page 12 of13 repaint() merely requests the AWT thread to call update(). It then returns immediately. This type of behaviour is called asynchronous. How the AWT thread reacts to the request is up to it. This behavour can lead to problems if you are not careful: Multiple repaint() requests can unintentionally be combined into one The behavour which causes the most trouble is the fact that the AWT may combine multiple rapid fire repaint() requests into one request. In practice this behaviour often means that only the last repaint() request in the sequence actually causes update() and paint() to be called. The result is that part of your beautiful drawing goes missing. This problem usually occurs when repaint() is being called from a program loop. Using Thread.sleep() to slow down repaint() requests On the other hand, some textbooks recommend that you use the Thread.sleep() method. The idea is to put, try { Thread.sleep(100); } catch(InterruptedException ex) {} either just before or just after the repaint() call. The Thread.sleep(100) puts the currently running thread to sleep for 100 milliseconds. This allows other threads, if there are any, a chance to run. When only the AWT thread is present This doesn't work! Putting the AWT thread to sleep solves nothing. Nothing happens, it wakes up, another repaint() request comes in but the AWT thread goes to sleep again. So the pile up of requests just gets frozen for the sleep time. In the end they are combined the same way as without the sleep and your drawing is still ruined. In a multithreaded program Using Thread.sleep() in a programmer created thread to slow down rapid fire repaint() calls solves the problem of combined repaint() requests. The AWT GUI thread keeps running and has time to deal with requests to update() and paint() because the thread which is the source of the requests is put to sleep periodically and thus slowed down. The AWT thread meanwhile goes on its merry way. getDocumentBase public URL getDocumentBase() Gets the URL of the document in which this applet is embedded. For example, suppose an applet is contained within the document: http://java.sun.com/products/jdk/1.2/index.html The document base is: http://java.sun.com/products/jdk/1.2/index.html Returns: the URL of the document that contains this applet.
  • 13.
    Page 13 of13 getCodeBase public URL getCodeBase() Gets the base URL. This is the URL of the directory which contains this applet. Returns: the base URL of the directory which contains this applet. Code for An applet program to give demo of getDocumentBase() and getCodeBase() methods in Java /* <applet code="URLDemo" height=100 width=400> </applet> */ import java.awt.*; import java.applet.*; import java.net.*; publicclass URLDemo extends Applet { publicvoid paint(Graphics g){ String msg; URL url=getCodeBase(); msg = "Code Base : "+url.toString(); g.drawString(msg,10,20); url=getDocumentBase(); msg="Document Base : "+url.toString(); g.drawString(msg,10,40); } }