SlideShare uma empresa Scribd logo
1 de 13
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,
parameterpassinginappletinapplets,conceptof delegationeventmodel and listener, I/O in applets, use of repaint(),
getDocumentBase(),getCodeBase()methods,layoutmanager(basicconcept),creationof buttons(JButton class only) &
text fields.
Java applet
A Javaappletisa small applicationwritteninJava,anddeliveredto usersinthe formof bytecode.The userlaunchesthe
Java appletfroma 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,andrunas part of a Web document.Afteranappletarrivesonthe client,it has limited access to resources, so
that itcan produce an arbitrarymultimediauserinterfaceandruncomplex computations withoutintroducingthe riskof
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 throughthe console-basedI/Oclasses.The AWT contains support for a window-based, graphical interface.
As youmightexpect,the AWTisquite large and sophisticated,andacomplete discussionof it isoutof the scope
of this note. Fortunately, this simple applet makes very limited use of the AWT.
Page 2 of 13
 The secondimportstatementimportsthe appletpackage,whichcontainsthe classApplet.Everyappletthat 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 windowinwhichthe appletisrunningcan be overwrittenbyanotherwindowandthenuncovered.Or, the
appletwindowcanbe minimizedandthenrestored,paint() isalsocalled when the applet begins execution. Whatever
the cause,wheneverthe appletmustredrawitsoutput,paint( ) iscalled.The paint( ) methodhasone parameterof type
Graphics.Thisparametercontainsthe graphicscontext,whichdescribesthe graphicsenvironmentinwhichthe appletis
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 isthe stringto be outputbeginningatx,y.Ina Java window,the upper-leftcorneris 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().Infact,most appletsdon’tevenhave amain( ) 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,runningSimpleAppletinvolvesadifferentprocess. Infact,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 anappletinaWeb browser,youneedtowrite 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 SimpleAppletwithanappletviewer,youmayalsoexecute the HTMLfile 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,amore convenientmethodexiststhatyoucan use to speeduptesting.Simplyincludea comment at the head
of yourJava source code file thatcontainsthe APPLETtag. By doingso,your code is documentedwithaprototype of the
necessaryHTML statements,andyoucan testyour compiledappletmerely 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,youcanquicklyiterate throughappletdevelopmentbyusingthese three steps:
 Edit a Java source file.
 Compile your program.
 Execute the appletviewer,specifyingthe name of yourapplet’ssource file.The appletviewerwill encounterthe
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/Ois notaccomplishedwithJava’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 Notpresent
Execution RequiresJRE Requiresabrowserlike Chrome
Nature Calledasstand-alone applicationasapplicationcanbe
executedfromcommandprompt
Requiressome thirdpartytool help like a
browsertoexecute
Restrictions Can accessany data or software available onthe system cannot accessany thingon the system
exceptbrowser’sservices
Security Doesnot require anysecurity Requireshighestsecurityforthe systemas
theyare untrusted
Advantages of Applets
1. Executionof appletsiseasyina Webbrowseranddoesnot require anyinstallationordeploymentprocedure in
realtime programming(whereasservletsrequire).
2. Writingand displaying(justopeninginabrowser) graphicsand animationsiseasierthanapplications.
Page 8 of 13
3. In GUI development,constructor,sizeof frame,windowclosingcode etc.are notrequired(butare requiredin
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. Appletsare treatedas untrusted(as theywere 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
Appletsare treatedas untrustedbecause theyare developed by somebody and placed on some unknown Web server.
Whendownloaded,theymayharmthe systemresourcesor 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.Browserdoesnotallowthe applettoaccessany of the systemresources(appletispermittedtouse browser
resources, infact, applet execution goes within the browser only).
 Appletsare notpermittedtouse anysystemresourceslike file systemastheyare untrustedandcan injectvirus
intothe system.
 Appletscannotreadfromor write to hard diskfiles.
 Appletmethodscannotbe native.
 Appletsshouldnotattempttocreate socketconnections
 Appletscannotreadsystemproperties
 Appletscannotuse anysoftware availableonthe system(exceptbrowserexecutionarea)
 Cannotcreate objectsof applicationsavailable onthe systembycomposition
The JRE throws SecurityExceptionif the appletviolatesthe browserrestrictions.
What is delegation event model in java?
Eventmodel isbasedonthe concept of an 'EventSource' and 'EventListeners'.Anyobjectthatisinterested 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 modernapproach to handlingeventsisbasedonthe delegationeventmodel,whichdefinesstandardandconsistent
mechanismstogenerate andprocessevents.Itsconceptisquite simple:asource generatesaneventandsendsitto one
or more listeners. In this scheme, the listener simply waits until it receives an event. Once received, the listener
processesthe eventandthenreturns.The advantage of thisdesignisthat 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 eventmodel isalsocalledthe "delegation"eventmodel because eventhandlingisdelegatedtodifferent
objectsandmethodsratherthan havingyourApplethandle all the events.
 The ideais that eventsare processedby eventlisteners,whichare separate objectsthathandle specifictypesof
events.
Note:Inorder to use the delegationeventmodel properly,the Appletshould notbe the listener.
 The listenerregistersandspecifieswhicheventsare of interest(forinstance mouseevents).
 Only those eventsthatare beinglistenedforwill be processed.
 Each differenteventtype usesaseparate Eventclass.
 Each differentkindof listeneralsousesaseparate class.
 Thismodel makeseventhandlingmore efficientbecausenotall eventshave to be processedandthe events
that are processedare onlysenttothe registeredlistenersratherthantoan entire hierarchyof eventhandlers.
 Thismodel alsoallowsyourApplettobe organizedsuchthatthe applicationcode andthe interface code (the
GUI) can be separated.
 Also,usingdifferenteventclassesallowsthe Javacompilertoperformmore specifictype errorchecking.
Event Listeners
An EventListener,once settoan appletobjectwaitsforsome actiontobe performedonit,be itmouse click,mouse
hover,pressingof keys,clickof button,etc.The classyouare using(e.g. JButton,etc.) reportsthe activityto a classset
by the classusingit.That methodthendecidesonhow toreact because of that action,usuallywithaseriesof if
statementstodeterminewhichactionitwasperformedon. source.getSource() will returnthe name of the object
that the eventwasperformedon,whilethe sourceisthe objectpassedtothe functionwhenthe actionisperformed.
Everysingle time the actionisperformed,itcallsthe 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 followingexample showshowtoimplement 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);
}
}
Whenyoucompile andrun the above code,a message will appearwhenyouclickonthe button.
The repaint() method-The GUI (AWT) Thread
One of a numberof systemthreads.Thisthreadisresponsible foracceptinginputeventsandcallingthe paint() method.
The programmershould leavecalling paint() to thisthread. Java appletsrarelycall paint() directly.
There are two wayspaint() calls are generated:
1. spontaneouspainting,initiatedbythe environment
2. programmergeneratedcallsviarepaint() andupdate()
Spontaneouscalls
In the firstcase,spontaneouspaintingreferstocallstopaint() fromthe browser.
The GUI thread makes these calls. Every applet or application with a GUI (i.e., a Frame) has a GUI thread.
There are foursituationswhenthe GUIthreadcallspaint() spontaneously.
1. a windowiscoveredbyanotherandthenre-exposed.Paint() iscalledtoreconstructthe damagedpartsof the
uncoveredwindow
2. afterdeiconification
3. inan appletafterinit() hasfinished
4. whena browserreturnstoa page whichcontainsanapplet,providedthe appletisatleastpartiallyexposed.
Therepaint()Method
The secondcase,whenpaint() callsare generetediswhenthe programcallsrepaint() orupdate().The repaint() method
isthe one invokedbyaprogram to do drawing.Theirare 4 versionsof thismethodbutthe one withno argumentsis
usuallyused.Drawingviarepaint() mostoftentakesplace inresponse touserinput.
repaint() ==> update() ==(usuallycalls)==> paint()
repaint() doesnotinvoke paint() directly.It schedules a call to an intermediate method,update().Finally,update() calls
paint() (unlessyouoverrideupdate).
Page 11 of 13
The reasonfor thiscomplexityisJava'ssupportforconcurrentprogramming.Itdoesthisusingthreads.
Usingrepaint()canbetricky foratleast three reasons.
1. the interactionbetweenrepaint()andthe spontaneouspaintingdone bythe GUIthread
2. the fact that repaint() justasksthe threadsystemtoschedule acall to update()/paint() andthenexits.The
repaint() methodis asynchronous.
3. the problemof preventingyourdrawingfrombeingerasedwhenbeingupdated.
All these potential complicationsare consideredindetailsbelow.
However,let'sstartwitha discussionwhathappensif paint() orupdate() are calleddirectly.
Using paint( ) and update() directly.
What isof concernhere iswhat happensif the user,forexample,coversall orpartof yourdrawingby anotherwindow,
and thenuncoversyourdrawingagain.Doesitsurvive?Similarly,whathappensif the userresizesthe browserwindow?
Whenpaint() is calledafterinit(),orafterthe applethasbeencoveredoriconified,itusesthe defaultpaint()whichjust
paintsthe background color,therebyerasingthe image.A paint() methodhasbeenadded.Thisworksbutthe method
paint() isoverlycomplex.
Thisis a simplerwaytodo it,because update() automaticallycoversthe drawingareawiththe backgroundcolour,
essentiallyanerasingoperation,andthen automaticallycallspaint().
Preventingerasingby update()
Why callingpaint()orupdate() directly isnot sucha goodidea
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
overlayingoriconifying/ deiconifying. If you have a complex paint() method and call it directly you may tie everything
else up,therebydegradingperformance anddefeatingthe multitaskingnature of Java. A bug in your code may not only
stop you applet but everything else running on the page as well.
Usingupdate()directly creates thesameproblems.
The repaint() methodisdesignedtoavoidthese problems.Howeveritcanbe tricky to use as itwas mentionedbefore
The behaviour of repaint()
The behaviourof the followingexampleisslightlydifferentfromthe previousexamples,if youonlyconsiderthe applet
inisolation.Inparticular,itimplementsthe differentinterface: MouseMotionListenerinterface.Butthe maindifference
isthat this versionismore 'polite'thanthe others:itusesrepaint.
If repaint() isjustcalledbyuserinteractionswithcomponentsyoushouldhave noproblemsusingrepaint() thisway.
However,if repaint() iscalledinatightloop,the AWT threadqueue maybe overwhelmedandstrange thingsmay
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 behavourwhichcausesthe mosttrouble isthe fact that the AWT may combinemultiplerapidfire repaint()
requests into one request.In practice thisbehaviouroftenmeansthatonlythe lastrepaint() requestinthe sequence
actuallycausesupdate() andpaint() tobe called.The resultisthatpart of your beautiful drawinggoesmissing.
This problem usually occurs when repaint() is being called from a program loop.
UsingThread.sleep()to slowdownrepaint()requests
On the otherhand,some textbooksrecommendthatyouuse the Thread.sleep() method.The ideaistoput,
try {
Thread.sleep(100);
}
catch(InterruptedException ex) {}
eitherjustbefore orjustafterthe repaint() call.The Thread.sleep(100) putsthe currentlyrunningthreadtosleepfor
100 milliseconds.Thisallowsotherthreads,if there are any,achance to run.
Whenonly the AWT thread is present
Thisdoesn'twork!Puttingthe AWT threadto sleepsolvesnothing.Nothinghappens,itwakesup,anotherrepaint()
requestcomesinbutthe AWT thread goesto sleepagain.Sothe pile upof requestsjustgetsfrozenforthe sleeptime.
In the endtheyare combinedthe same wayaswithout the sleepandyourdrawingisstill ruined.
In a multithreaded program
UsingThread.sleep() inaprogrammercreatedthreadtoslow downrapidfire repaint() callssolvesthe problemof
combinedrepaint() requests.The AWTGUI threadkeepsrunningandhastime to deal withrequeststoupdate() and
paint() because the threadwhichisthe source of the requestsisputto sleepperiodicallyandthussloweddown.The
AWT threadmeanwhilegoesonitsmerryway.
getDocumentBase
public URL getDocumentBase()
Gets the URL of the documentinwhichthisappletisembedded.Forexample,suppose anappletiscontained
withinthe document:
http://java.sun.com/products/jdk/1.2/index.html
The documentbase is:
http://java.sun.com/products/jdk/1.2/index.html
Returns: the URL of the documentthatcontainsthisapplet.
Page 13 of 13
getCodeBase
public URL getCodeBase()
Gets the base URL. This isthe URL of the directorywhichcontainsthisapplet.
Returns:
the base URL of the directorywhichcontainsthisapplet.
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);
}
}

Mais conteúdo relacionado

Mais procurados (20)

Appletjava
AppletjavaAppletjava
Appletjava
 
Applet programming in java
Applet programming in javaApplet programming in java
Applet programming in java
 
L18 applets
L18 appletsL18 applets
L18 applets
 
Java Applet
Java AppletJava Applet
Java Applet
 
Basics of applets.53
Basics of applets.53Basics of applets.53
Basics of applets.53
 
Java Applets
Java AppletsJava Applets
Java Applets
 
Java applets
Java appletsJava applets
Java applets
 
ITFT- Applet in java
ITFT- Applet in javaITFT- Applet in java
ITFT- Applet in java
 
Appl clas nd architect.56
Appl clas nd architect.56Appl clas nd architect.56
Appl clas nd architect.56
 
Java: Java Applets
Java: Java AppletsJava: Java Applets
Java: Java Applets
 
Java Applet
Java AppletJava Applet
Java Applet
 
Applets
AppletsApplets
Applets
 
first-applet
first-appletfirst-applet
first-applet
 
6.applet programming in java
6.applet programming in java6.applet programming in java
6.applet programming in java
 
Applet in java
Applet in javaApplet in java
Applet in java
 
Java applets
Java appletsJava applets
Java applets
 
Applet init nd termination.59
Applet init nd termination.59Applet init nd termination.59
Applet init nd termination.59
 
JAVA INTRODUCTION
JAVA INTRODUCTIONJAVA INTRODUCTION
JAVA INTRODUCTION
 
Java applet
Java appletJava applet
Java applet
 
Slide8appletv2 091028110313-phpapp01
Slide8appletv2 091028110313-phpapp01Slide8appletv2 091028110313-phpapp01
Slide8appletv2 091028110313-phpapp01
 

Semelhante a Class Notes on Applet Programming

Semelhante a Class Notes on Applet Programming (20)

UNIT-1-AJAVA.pdf
UNIT-1-AJAVA.pdfUNIT-1-AJAVA.pdf
UNIT-1-AJAVA.pdf
 
oops with java modules iii & iv.pptx
oops with java modules iii & iv.pptxoops with java modules iii & iv.pptx
oops with java modules iii & iv.pptx
 
Lecture1 oopj
Lecture1 oopjLecture1 oopj
Lecture1 oopj
 
Java applet-basics
Java applet-basicsJava applet-basics
Java applet-basics
 
Java applet-basics
Java applet-basicsJava applet-basics
Java applet-basics
 
Applet1 (1).pptx
Applet1 (1).pptxApplet1 (1).pptx
Applet1 (1).pptx
 
Java applet
Java appletJava applet
Java applet
 
Java
JavaJava
Java
 
Java files and io streams
Java files and io streamsJava files and io streams
Java files and io streams
 
JAVA INTRODUCTION
JAVA INTRODUCTIONJAVA INTRODUCTION
JAVA INTRODUCTION
 
Applets in Java
Applets in JavaApplets in Java
Applets in Java
 
Applet Architecture - Introducing Java Applets
Applet Architecture - Introducing Java AppletsApplet Architecture - Introducing Java Applets
Applet Architecture - Introducing Java Applets
 
APPLET.pptx
APPLET.pptxAPPLET.pptx
APPLET.pptx
 
Unit 7 Java
Unit 7 JavaUnit 7 Java
Unit 7 Java
 
Applet in java new
Applet in java newApplet in java new
Applet in java new
 
Applet (1)
Applet (1)Applet (1)
Applet (1)
 
Java basics notes
Java basics notesJava basics notes
Java basics notes
 
Java programming basics notes for beginners(java programming tutorials)
Java programming basics notes for beginners(java programming tutorials)Java programming basics notes for beginners(java programming tutorials)
Java programming basics notes for beginners(java programming tutorials)
 
Java basics notes
Java basics notesJava basics notes
Java basics notes
 
Java Applets
Java AppletsJava Applets
Java Applets
 

Mais de Kuntal Bhowmick

Multiple Choice Questions on JAVA (object oriented programming) bank 8 -- int...
Multiple Choice Questions on JAVA (object oriented programming) bank 8 -- int...Multiple Choice Questions on JAVA (object oriented programming) bank 8 -- int...
Multiple Choice Questions on JAVA (object oriented programming) bank 8 -- int...Kuntal Bhowmick
 
Multiple Choice Questions on JAVA (object oriented programming) bank 7 -- abs...
Multiple Choice Questions on JAVA (object oriented programming) bank 7 -- abs...Multiple Choice Questions on JAVA (object oriented programming) bank 7 -- abs...
Multiple Choice Questions on JAVA (object oriented programming) bank 7 -- abs...Kuntal Bhowmick
 
Multiple Choice Questions on JAVA (object oriented programming) bank 6 -- inh...
Multiple Choice Questions on JAVA (object oriented programming) bank 6 -- inh...Multiple Choice Questions on JAVA (object oriented programming) bank 6 -- inh...
Multiple Choice Questions on JAVA (object oriented programming) bank 6 -- inh...Kuntal Bhowmick
 
Multiple Choice Questions on JAVA (object oriented programming) bank 5 -- mem...
Multiple Choice Questions on JAVA (object oriented programming) bank 5 -- mem...Multiple Choice Questions on JAVA (object oriented programming) bank 5 -- mem...
Multiple Choice Questions on JAVA (object oriented programming) bank 5 -- mem...Kuntal Bhowmick
 
Multiple Choice Questions on JAVA (object oriented programming) bank 4 -- loops
Multiple Choice Questions on JAVA (object oriented programming) bank 4 -- loopsMultiple Choice Questions on JAVA (object oriented programming) bank 4 -- loops
Multiple Choice Questions on JAVA (object oriented programming) bank 4 -- loopsKuntal Bhowmick
 
Multiple Choice Questions on JAVA (object oriented programming) bank 3 -- cla...
Multiple Choice Questions on JAVA (object oriented programming) bank 3 -- cla...Multiple Choice Questions on JAVA (object oriented programming) bank 3 -- cla...
Multiple Choice Questions on JAVA (object oriented programming) bank 3 -- cla...Kuntal Bhowmick
 
Multiple Choice Questions on JAVA (object oriented programming) bank 2 -- bas...
Multiple Choice Questions on JAVA (object oriented programming) bank 2 -- bas...Multiple Choice Questions on JAVA (object oriented programming) bank 2 -- bas...
Multiple Choice Questions on JAVA (object oriented programming) bank 2 -- bas...Kuntal Bhowmick
 
Multiple Choice Questions on JAVA (object oriented programming) bank 1 -- int...
Multiple Choice Questions on JAVA (object oriented programming) bank 1 -- int...Multiple Choice Questions on JAVA (object oriented programming) bank 1 -- int...
Multiple Choice Questions on JAVA (object oriented programming) bank 1 -- int...Kuntal Bhowmick
 
Hashing notes data structures (HASHING AND HASH FUNCTIONS)
Hashing notes data structures (HASHING AND HASH FUNCTIONS)Hashing notes data structures (HASHING AND HASH FUNCTIONS)
Hashing notes data structures (HASHING AND HASH FUNCTIONS)Kuntal Bhowmick
 
1. introduction to E-commerce
1. introduction to E-commerce1. introduction to E-commerce
1. introduction to E-commerceKuntal Bhowmick
 
Computer graphics question for exam solved
Computer graphics question for exam solvedComputer graphics question for exam solved
Computer graphics question for exam solvedKuntal Bhowmick
 
DBMS and Rdbms fundamental concepts
DBMS and Rdbms fundamental conceptsDBMS and Rdbms fundamental concepts
DBMS and Rdbms fundamental conceptsKuntal Bhowmick
 
Java questions for interview
Java questions for interviewJava questions for interview
Java questions for interviewKuntal Bhowmick
 
Java Interview Questions
Java Interview QuestionsJava Interview Questions
Java Interview QuestionsKuntal Bhowmick
 
Operating system Interview Questions
Operating system Interview QuestionsOperating system Interview Questions
Operating system Interview QuestionsKuntal Bhowmick
 
Computer Network Interview Questions
Computer Network Interview QuestionsComputer Network Interview Questions
Computer Network Interview QuestionsKuntal Bhowmick
 
Distributed operating systems cs704 a class test
Distributed operating systems cs704 a class testDistributed operating systems cs704 a class test
Distributed operating systems cs704 a class testKuntal Bhowmick
 
Cs291 assignment solution
Cs291 assignment solutionCs291 assignment solution
Cs291 assignment solutionKuntal Bhowmick
 

Mais de Kuntal Bhowmick (20)

Multiple Choice Questions on JAVA (object oriented programming) bank 8 -- int...
Multiple Choice Questions on JAVA (object oriented programming) bank 8 -- int...Multiple Choice Questions on JAVA (object oriented programming) bank 8 -- int...
Multiple Choice Questions on JAVA (object oriented programming) bank 8 -- int...
 
Multiple Choice Questions on JAVA (object oriented programming) bank 7 -- abs...
Multiple Choice Questions on JAVA (object oriented programming) bank 7 -- abs...Multiple Choice Questions on JAVA (object oriented programming) bank 7 -- abs...
Multiple Choice Questions on JAVA (object oriented programming) bank 7 -- abs...
 
Multiple Choice Questions on JAVA (object oriented programming) bank 6 -- inh...
Multiple Choice Questions on JAVA (object oriented programming) bank 6 -- inh...Multiple Choice Questions on JAVA (object oriented programming) bank 6 -- inh...
Multiple Choice Questions on JAVA (object oriented programming) bank 6 -- inh...
 
Multiple Choice Questions on JAVA (object oriented programming) bank 5 -- mem...
Multiple Choice Questions on JAVA (object oriented programming) bank 5 -- mem...Multiple Choice Questions on JAVA (object oriented programming) bank 5 -- mem...
Multiple Choice Questions on JAVA (object oriented programming) bank 5 -- mem...
 
Multiple Choice Questions on JAVA (object oriented programming) bank 4 -- loops
Multiple Choice Questions on JAVA (object oriented programming) bank 4 -- loopsMultiple Choice Questions on JAVA (object oriented programming) bank 4 -- loops
Multiple Choice Questions on JAVA (object oriented programming) bank 4 -- loops
 
Multiple Choice Questions on JAVA (object oriented programming) bank 3 -- cla...
Multiple Choice Questions on JAVA (object oriented programming) bank 3 -- cla...Multiple Choice Questions on JAVA (object oriented programming) bank 3 -- cla...
Multiple Choice Questions on JAVA (object oriented programming) bank 3 -- cla...
 
Multiple Choice Questions on JAVA (object oriented programming) bank 2 -- bas...
Multiple Choice Questions on JAVA (object oriented programming) bank 2 -- bas...Multiple Choice Questions on JAVA (object oriented programming) bank 2 -- bas...
Multiple Choice Questions on JAVA (object oriented programming) bank 2 -- bas...
 
Multiple Choice Questions on JAVA (object oriented programming) bank 1 -- int...
Multiple Choice Questions on JAVA (object oriented programming) bank 1 -- int...Multiple Choice Questions on JAVA (object oriented programming) bank 1 -- int...
Multiple Choice Questions on JAVA (object oriented programming) bank 1 -- int...
 
Hashing notes data structures (HASHING AND HASH FUNCTIONS)
Hashing notes data structures (HASHING AND HASH FUNCTIONS)Hashing notes data structures (HASHING AND HASH FUNCTIONS)
Hashing notes data structures (HASHING AND HASH FUNCTIONS)
 
1. introduction to E-commerce
1. introduction to E-commerce1. introduction to E-commerce
1. introduction to E-commerce
 
Computer graphics question for exam solved
Computer graphics question for exam solvedComputer graphics question for exam solved
Computer graphics question for exam solved
 
DBMS and Rdbms fundamental concepts
DBMS and Rdbms fundamental conceptsDBMS and Rdbms fundamental concepts
DBMS and Rdbms fundamental concepts
 
Java questions for interview
Java questions for interviewJava questions for interview
Java questions for interview
 
Java Interview Questions
Java Interview QuestionsJava Interview Questions
Java Interview Questions
 
Operating system Interview Questions
Operating system Interview QuestionsOperating system Interview Questions
Operating system Interview Questions
 
Computer Network Interview Questions
Computer Network Interview QuestionsComputer Network Interview Questions
Computer Network Interview Questions
 
C interview questions
C interview  questionsC interview  questions
C interview questions
 
C question
C questionC question
C question
 
Distributed operating systems cs704 a class test
Distributed operating systems cs704 a class testDistributed operating systems cs704 a class test
Distributed operating systems cs704 a class test
 
Cs291 assignment solution
Cs291 assignment solutionCs291 assignment solution
Cs291 assignment solution
 

Último

Comparative study of High-rise Building Using ETABS,SAP200 and SAFE., SAFE an...
Comparative study of High-rise Building Using ETABS,SAP200 and SAFE., SAFE an...Comparative study of High-rise Building Using ETABS,SAP200 and SAFE., SAFE an...
Comparative study of High-rise Building Using ETABS,SAP200 and SAFE., SAFE an...Erbil Polytechnic University
 
List of Accredited Concrete Batching Plant.pdf
List of Accredited Concrete Batching Plant.pdfList of Accredited Concrete Batching Plant.pdf
List of Accredited Concrete Batching Plant.pdfisabel213075
 
"Exploring the Essential Functions and Design Considerations of Spillways in ...
"Exploring the Essential Functions and Design Considerations of Spillways in ..."Exploring the Essential Functions and Design Considerations of Spillways in ...
"Exploring the Essential Functions and Design Considerations of Spillways in ...Erbil Polytechnic University
 
DEVICE DRIVERS AND INTERRUPTS SERVICE MECHANISM.pdf
DEVICE DRIVERS AND INTERRUPTS  SERVICE MECHANISM.pdfDEVICE DRIVERS AND INTERRUPTS  SERVICE MECHANISM.pdf
DEVICE DRIVERS AND INTERRUPTS SERVICE MECHANISM.pdfAkritiPradhan2
 
Paper Tube : Shigeru Ban projects and Case Study of Cardboard Cathedral .pdf
Paper Tube : Shigeru Ban projects and Case Study of Cardboard Cathedral .pdfPaper Tube : Shigeru Ban projects and Case Study of Cardboard Cathedral .pdf
Paper Tube : Shigeru Ban projects and Case Study of Cardboard Cathedral .pdfNainaShrivastava14
 
CS 3251 Programming in c all unit notes pdf
CS 3251 Programming in c all unit notes pdfCS 3251 Programming in c all unit notes pdf
CS 3251 Programming in c all unit notes pdfBalamuruganV28
 
Mine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptxMine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptxRomil Mishra
 
Input Output Management in Operating System
Input Output Management in Operating SystemInput Output Management in Operating System
Input Output Management in Operating SystemRashmi Bhat
 
Cost estimation approach: FP to COCOMO scenario based question
Cost estimation approach: FP to COCOMO scenario based questionCost estimation approach: FP to COCOMO scenario based question
Cost estimation approach: FP to COCOMO scenario based questionSneha Padhiar
 
OOP concepts -in-Python programming language
OOP concepts -in-Python programming languageOOP concepts -in-Python programming language
OOP concepts -in-Python programming languageSmritiSharma901052
 
KCD Costa Rica 2024 - Nephio para parvulitos
KCD Costa Rica 2024 - Nephio para parvulitosKCD Costa Rica 2024 - Nephio para parvulitos
KCD Costa Rica 2024 - Nephio para parvulitosVictor Morales
 
signals in triangulation .. ...Surveying
signals in triangulation .. ...Surveyingsignals in triangulation .. ...Surveying
signals in triangulation .. ...Surveyingsapna80328
 
Engineering Drawing section of solid
Engineering Drawing     section of solidEngineering Drawing     section of solid
Engineering Drawing section of solidnamansinghjarodiya
 
High Voltage Engineering- OVER VOLTAGES IN ELECTRICAL POWER SYSTEMS
High Voltage Engineering- OVER VOLTAGES IN ELECTRICAL POWER SYSTEMSHigh Voltage Engineering- OVER VOLTAGES IN ELECTRICAL POWER SYSTEMS
High Voltage Engineering- OVER VOLTAGES IN ELECTRICAL POWER SYSTEMSsandhya757531
 
Module-1-(Building Acoustics) Noise Control (Unit-3). pdf
Module-1-(Building Acoustics) Noise Control (Unit-3). pdfModule-1-(Building Acoustics) Noise Control (Unit-3). pdf
Module-1-(Building Acoustics) Noise Control (Unit-3). pdfManish Kumar
 
Gravity concentration_MI20612MI_________
Gravity concentration_MI20612MI_________Gravity concentration_MI20612MI_________
Gravity concentration_MI20612MI_________Romil Mishra
 
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTIONTHE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTIONjhunlian
 
Artificial Intelligence in Power System overview
Artificial Intelligence in Power System overviewArtificial Intelligence in Power System overview
Artificial Intelligence in Power System overviewsandhya757531
 
Earthing details of Electrical Substation
Earthing details of Electrical SubstationEarthing details of Electrical Substation
Earthing details of Electrical Substationstephanwindworld
 

Último (20)

Comparative study of High-rise Building Using ETABS,SAP200 and SAFE., SAFE an...
Comparative study of High-rise Building Using ETABS,SAP200 and SAFE., SAFE an...Comparative study of High-rise Building Using ETABS,SAP200 and SAFE., SAFE an...
Comparative study of High-rise Building Using ETABS,SAP200 and SAFE., SAFE an...
 
List of Accredited Concrete Batching Plant.pdf
List of Accredited Concrete Batching Plant.pdfList of Accredited Concrete Batching Plant.pdf
List of Accredited Concrete Batching Plant.pdf
 
"Exploring the Essential Functions and Design Considerations of Spillways in ...
"Exploring the Essential Functions and Design Considerations of Spillways in ..."Exploring the Essential Functions and Design Considerations of Spillways in ...
"Exploring the Essential Functions and Design Considerations of Spillways in ...
 
DEVICE DRIVERS AND INTERRUPTS SERVICE MECHANISM.pdf
DEVICE DRIVERS AND INTERRUPTS  SERVICE MECHANISM.pdfDEVICE DRIVERS AND INTERRUPTS  SERVICE MECHANISM.pdf
DEVICE DRIVERS AND INTERRUPTS SERVICE MECHANISM.pdf
 
Paper Tube : Shigeru Ban projects and Case Study of Cardboard Cathedral .pdf
Paper Tube : Shigeru Ban projects and Case Study of Cardboard Cathedral .pdfPaper Tube : Shigeru Ban projects and Case Study of Cardboard Cathedral .pdf
Paper Tube : Shigeru Ban projects and Case Study of Cardboard Cathedral .pdf
 
CS 3251 Programming in c all unit notes pdf
CS 3251 Programming in c all unit notes pdfCS 3251 Programming in c all unit notes pdf
CS 3251 Programming in c all unit notes pdf
 
Mine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptxMine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptx
 
Input Output Management in Operating System
Input Output Management in Operating SystemInput Output Management in Operating System
Input Output Management in Operating System
 
Cost estimation approach: FP to COCOMO scenario based question
Cost estimation approach: FP to COCOMO scenario based questionCost estimation approach: FP to COCOMO scenario based question
Cost estimation approach: FP to COCOMO scenario based question
 
OOP concepts -in-Python programming language
OOP concepts -in-Python programming languageOOP concepts -in-Python programming language
OOP concepts -in-Python programming language
 
KCD Costa Rica 2024 - Nephio para parvulitos
KCD Costa Rica 2024 - Nephio para parvulitosKCD Costa Rica 2024 - Nephio para parvulitos
KCD Costa Rica 2024 - Nephio para parvulitos
 
signals in triangulation .. ...Surveying
signals in triangulation .. ...Surveyingsignals in triangulation .. ...Surveying
signals in triangulation .. ...Surveying
 
Engineering Drawing section of solid
Engineering Drawing     section of solidEngineering Drawing     section of solid
Engineering Drawing section of solid
 
High Voltage Engineering- OVER VOLTAGES IN ELECTRICAL POWER SYSTEMS
High Voltage Engineering- OVER VOLTAGES IN ELECTRICAL POWER SYSTEMSHigh Voltage Engineering- OVER VOLTAGES IN ELECTRICAL POWER SYSTEMS
High Voltage Engineering- OVER VOLTAGES IN ELECTRICAL POWER SYSTEMS
 
Designing pile caps according to ACI 318-19.pptx
Designing pile caps according to ACI 318-19.pptxDesigning pile caps according to ACI 318-19.pptx
Designing pile caps according to ACI 318-19.pptx
 
Module-1-(Building Acoustics) Noise Control (Unit-3). pdf
Module-1-(Building Acoustics) Noise Control (Unit-3). pdfModule-1-(Building Acoustics) Noise Control (Unit-3). pdf
Module-1-(Building Acoustics) Noise Control (Unit-3). pdf
 
Gravity concentration_MI20612MI_________
Gravity concentration_MI20612MI_________Gravity concentration_MI20612MI_________
Gravity concentration_MI20612MI_________
 
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTIONTHE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
 
Artificial Intelligence in Power System overview
Artificial Intelligence in Power System overviewArtificial Intelligence in Power System overview
Artificial Intelligence in Power System overview
 
Earthing details of Electrical Substation
Earthing details of Electrical SubstationEarthing details of Electrical Substation
Earthing details of Electrical Substation
 

Class Notes on Applet Programming

  • 1. 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, parameterpassinginappletinapplets,conceptof delegationeventmodel and listener, I/O in applets, use of repaint(), getDocumentBase(),getCodeBase()methods,layoutmanager(basicconcept),creationof buttons(JButton class only) & text fields. Java applet A Javaappletisa small applicationwritteninJava,anddeliveredto usersinthe formof bytecode.The userlaunchesthe Java appletfroma 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,andrunas part of a Web document.Afteranappletarrivesonthe client,it has limited access to resources, so that itcan produce an arbitrarymultimediauserinterfaceandruncomplex computations withoutintroducingthe riskof 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 throughthe console-basedI/Oclasses.The AWT contains support for a window-based, graphical interface. As youmightexpect,the AWTisquite large and sophisticated,andacomplete discussionof it isoutof the scope of this note. Fortunately, this simple applet makes very limited use of the AWT.
  • 2. Page 2 of 13  The secondimportstatementimportsthe appletpackage,whichcontainsthe classApplet.Everyappletthat 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 windowinwhichthe appletisrunningcan be overwrittenbyanotherwindowandthenuncovered.Or, the appletwindowcanbe minimizedandthenrestored,paint() isalsocalled when the applet begins execution. Whatever the cause,wheneverthe appletmustredrawitsoutput,paint( ) iscalled.The paint( ) methodhasone parameterof type Graphics.Thisparametercontainsthe graphicscontext,whichdescribesthe graphicsenvironmentinwhichthe appletis 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 isthe stringto be outputbeginningatx,y.Ina Java window,the upper-leftcorneris 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().Infact,most appletsdon’tevenhave amain( ) 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,runningSimpleAppletinvolvesadifferentprocess. Infact,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 of 13 Each of these methods is described next. To execute anappletinaWeb browser,youneedtowrite 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 SimpleAppletwithanappletviewer,youmayalsoexecute the HTMLfile 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,amore convenientmethodexiststhatyoucan use to speeduptesting.Simplyincludea comment at the head of yourJava source code file thatcontainsthe APPLETtag. By doingso,your code is documentedwithaprototype of the necessaryHTML statements,andyoucan testyour compiledappletmerely 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,youcanquicklyiterate throughappletdevelopmentbyusingthese three steps:  Edit a Java source file.  Compile your program.  Execute the appletviewer,specifyingthe name of yourapplet’ssource file.The appletviewerwill encounterthe 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 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/Ois notaccomplishedwithJava’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 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.
  • 7. Page 7 of 13 Applications Vs. Applets Feature Application Applet main() method Present Notpresent Execution RequiresJRE Requiresabrowserlike Chrome Nature Calledasstand-alone applicationasapplicationcanbe executedfromcommandprompt Requiressome thirdpartytool help like a browsertoexecute Restrictions Can accessany data or software available onthe system cannot accessany thingon the system exceptbrowser’sservices Security Doesnot require anysecurity Requireshighestsecurityforthe systemas theyare untrusted Advantages of Applets 1. Executionof appletsiseasyina Webbrowseranddoesnot require anyinstallationordeploymentprocedure in realtime programming(whereasservletsrequire). 2. Writingand displaying(justopeninginabrowser) graphicsand animationsiseasierthanapplications.
  • 8. Page 8 of 13 3. In GUI development,constructor,sizeof frame,windowclosingcode etc.are notrequired(butare requiredin 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. Appletsare treatedas untrusted(as theywere 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 Appletsare treatedas untrustedbecause theyare developed by somebody and placed on some unknown Web server. Whendownloaded,theymayharmthe systemresourcesor 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.Browserdoesnotallowthe applettoaccessany of the systemresources(appletispermittedtouse browser resources, infact, applet execution goes within the browser only).  Appletsare notpermittedtouse anysystemresourceslike file systemastheyare untrustedandcan injectvirus intothe system.  Appletscannotreadfromor write to hard diskfiles.  Appletmethodscannotbe native.  Appletsshouldnotattempttocreate socketconnections  Appletscannotreadsystemproperties  Appletscannotuse anysoftware availableonthe system(exceptbrowserexecutionarea)  Cannotcreate objectsof applicationsavailable onthe systembycomposition The JRE throws SecurityExceptionif the appletviolatesthe browserrestrictions. What is delegation event model in java? Eventmodel isbasedonthe concept of an 'EventSource' and 'EventListeners'.Anyobjectthatisinterested 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 modernapproach to handlingeventsisbasedonthe delegationeventmodel,whichdefinesstandardandconsistent mechanismstogenerate andprocessevents.Itsconceptisquite simple:asource generatesaneventandsendsitto one or more listeners. In this scheme, the listener simply waits until it receives an event. Once received, the listener processesthe eventandthenreturns.The advantage of thisdesignisthat 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 of 13 Overview of the Delegation Event Model  The 1.1 eventmodel isalsocalledthe "delegation"eventmodel because eventhandlingisdelegatedtodifferent objectsandmethodsratherthan havingyourApplethandle all the events.  The ideais that eventsare processedby eventlisteners,whichare separate objectsthathandle specifictypesof events. Note:Inorder to use the delegationeventmodel properly,the Appletshould notbe the listener.  The listenerregistersandspecifieswhicheventsare of interest(forinstance mouseevents).  Only those eventsthatare beinglistenedforwill be processed.  Each differenteventtype usesaseparate Eventclass.  Each differentkindof listeneralsousesaseparate class.  Thismodel makeseventhandlingmore efficientbecausenotall eventshave to be processedandthe events that are processedare onlysenttothe registeredlistenersratherthantoan entire hierarchyof eventhandlers.  Thismodel alsoallowsyourApplettobe organizedsuchthatthe applicationcode andthe interface code (the GUI) can be separated.  Also,usingdifferenteventclassesallowsthe Javacompilertoperformmore specifictype errorchecking. Event Listeners An EventListener,once settoan appletobjectwaitsforsome actiontobe performedonit,be itmouse click,mouse hover,pressingof keys,clickof button,etc.The classyouare using(e.g. JButton,etc.) reportsthe activityto a classset by the classusingit.That methodthendecidesonhow toreact because of that action,usuallywithaseriesof if statementstodeterminewhichactionitwasperformedon. source.getSource() will returnthe name of the object that the eventwasperformedon,whilethe sourceisthe objectpassedtothe functionwhenthe actionisperformed. Everysingle time the actionisperformed,itcallsthe 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 followingexample showshowtoimplement 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 of 13 public static void main(String[] args) { new ActionDemo().setVisible(true); } } Whenyoucompile andrun the above code,a message will appearwhenyouclickonthe button. The repaint() method-The GUI (AWT) Thread One of a numberof systemthreads.Thisthreadisresponsible foracceptinginputeventsandcallingthe paint() method. The programmershould leavecalling paint() to thisthread. Java appletsrarelycall paint() directly. There are two wayspaint() calls are generated: 1. spontaneouspainting,initiatedbythe environment 2. programmergeneratedcallsviarepaint() andupdate() Spontaneouscalls In the firstcase,spontaneouspaintingreferstocallstopaint() fromthe browser. The GUI thread makes these calls. Every applet or application with a GUI (i.e., a Frame) has a GUI thread. There are foursituationswhenthe GUIthreadcallspaint() spontaneously. 1. a windowiscoveredbyanotherandthenre-exposed.Paint() iscalledtoreconstructthe damagedpartsof the uncoveredwindow 2. afterdeiconification 3. inan appletafterinit() hasfinished 4. whena browserreturnstoa page whichcontainsanapplet,providedthe appletisatleastpartiallyexposed. Therepaint()Method The secondcase,whenpaint() callsare generetediswhenthe programcallsrepaint() orupdate().The repaint() method isthe one invokedbyaprogram to do drawing.Theirare 4 versionsof thismethodbutthe one withno argumentsis usuallyused.Drawingviarepaint() mostoftentakesplace inresponse touserinput. repaint() ==> update() ==(usuallycalls)==> paint() repaint() doesnotinvoke paint() directly.It schedules a call to an intermediate method,update().Finally,update() calls paint() (unlessyouoverrideupdate).
  • 11. Page 11 of 13 The reasonfor thiscomplexityisJava'ssupportforconcurrentprogramming.Itdoesthisusingthreads. Usingrepaint()canbetricky foratleast three reasons. 1. the interactionbetweenrepaint()andthe spontaneouspaintingdone bythe GUIthread 2. the fact that repaint() justasksthe threadsystemtoschedule acall to update()/paint() andthenexits.The repaint() methodis asynchronous. 3. the problemof preventingyourdrawingfrombeingerasedwhenbeingupdated. All these potential complicationsare consideredindetailsbelow. However,let'sstartwitha discussionwhathappensif paint() orupdate() are calleddirectly. Using paint( ) and update() directly. What isof concernhere iswhat happensif the user,forexample,coversall orpartof yourdrawingby anotherwindow, and thenuncoversyourdrawingagain.Doesitsurvive?Similarly,whathappensif the userresizesthe browserwindow? Whenpaint() is calledafterinit(),orafterthe applethasbeencoveredoriconified,itusesthe defaultpaint()whichjust paintsthe background color,therebyerasingthe image.A paint() methodhasbeenadded.Thisworksbutthe method paint() isoverlycomplex. Thisis a simplerwaytodo it,because update() automaticallycoversthe drawingareawiththe backgroundcolour, essentiallyanerasingoperation,andthen automaticallycallspaint(). Preventingerasingby update() Why callingpaint()orupdate() directly isnot sucha goodidea 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 overlayingoriconifying/ deiconifying. If you have a complex paint() method and call it directly you may tie everything else up,therebydegradingperformance anddefeatingthe multitaskingnature of Java. A bug in your code may not only stop you applet but everything else running on the page as well. Usingupdate()directly creates thesameproblems. The repaint() methodisdesignedtoavoidthese problems.Howeveritcanbe tricky to use as itwas mentionedbefore The behaviour of repaint() The behaviourof the followingexampleisslightlydifferentfromthe previousexamples,if youonlyconsiderthe applet inisolation.Inparticular,itimplementsthe differentinterface: MouseMotionListenerinterface.Butthe maindifference isthat this versionismore 'polite'thanthe others:itusesrepaint. If repaint() isjustcalledbyuserinteractionswithcomponentsyoushouldhave noproblemsusingrepaint() thisway. However,if repaint() iscalledinatightloop,the AWT threadqueue maybe overwhelmedandstrange thingsmay happen.
  • 12. 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 behavourwhichcausesthe mosttrouble isthe fact that the AWT may combinemultiplerapidfire repaint() requests into one request.In practice thisbehaviouroftenmeansthatonlythe lastrepaint() requestinthe sequence actuallycausesupdate() andpaint() tobe called.The resultisthatpart of your beautiful drawinggoesmissing. This problem usually occurs when repaint() is being called from a program loop. UsingThread.sleep()to slowdownrepaint()requests On the otherhand,some textbooksrecommendthatyouuse the Thread.sleep() method.The ideaistoput, try { Thread.sleep(100); } catch(InterruptedException ex) {} eitherjustbefore orjustafterthe repaint() call.The Thread.sleep(100) putsthe currentlyrunningthreadtosleepfor 100 milliseconds.Thisallowsotherthreads,if there are any,achance to run. Whenonly the AWT thread is present Thisdoesn'twork!Puttingthe AWT threadto sleepsolvesnothing.Nothinghappens,itwakesup,anotherrepaint() requestcomesinbutthe AWT thread goesto sleepagain.Sothe pile upof requestsjustgetsfrozenforthe sleeptime. In the endtheyare combinedthe same wayaswithout the sleepandyourdrawingisstill ruined. In a multithreaded program UsingThread.sleep() inaprogrammercreatedthreadtoslow downrapidfire repaint() callssolvesthe problemof combinedrepaint() requests.The AWTGUI threadkeepsrunningandhastime to deal withrequeststoupdate() and paint() because the threadwhichisthe source of the requestsisputto sleepperiodicallyandthussloweddown.The AWT threadmeanwhilegoesonitsmerryway. getDocumentBase public URL getDocumentBase() Gets the URL of the documentinwhichthisappletisembedded.Forexample,suppose anappletiscontained withinthe document: http://java.sun.com/products/jdk/1.2/index.html The documentbase is: http://java.sun.com/products/jdk/1.2/index.html Returns: the URL of the documentthatcontainsthisapplet.
  • 13. Page 13 of 13 getCodeBase public URL getCodeBase() Gets the base URL. This isthe URL of the directorywhichcontainsthisapplet. Returns: the base URL of the directorywhichcontainsthisapplet. 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); } }