SlideShare a Scribd company logo
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);
}
}

More Related Content

What's hot (20)

PPTX
Appletjava
DEEPIKA T
 
PPTX
Applet programming in java
Vidya Bharti
 
PPTX
L18 applets
teach4uin
 
PPT
Basics of applets.53
myrajendra
 
PPTX
Java Applets
Danial Mirza
 
PPT
Java applets
M Vishnuvardhan Reddy
 
PDF
ITFT- Applet in java
Atul Sehdev
 
PPT
Appl clas nd architect.56
myrajendra
 
PPT
Java: Java Applets
Tareq Hasan
 
PPT
Java Applet
Athharul Haq
 
ODP
Applets
radon2569
 
PPT
first-applet
Mohit Patodia
 
PPTX
6.applet programming in java
Deepak Sharma
 
PDF
Applet in java
Jancypriya M
 
PPT
Java applets
Khan Mac-arther
 
PPT
Applet init nd termination.59
myrajendra
 
PDF
JAVA INTRODUCTION
Prof Ansari
 
PPTX
Java applet
Rohan Gajre
 
PPT
Slide8appletv2 091028110313-phpapp01
Abhishek Khune
 
Appletjava
DEEPIKA T
 
Applet programming in java
Vidya Bharti
 
L18 applets
teach4uin
 
Basics of applets.53
myrajendra
 
Java Applets
Danial Mirza
 
Java applets
M Vishnuvardhan Reddy
 
ITFT- Applet in java
Atul Sehdev
 
Appl clas nd architect.56
myrajendra
 
Java: Java Applets
Tareq Hasan
 
Java Applet
Athharul Haq
 
Applets
radon2569
 
first-applet
Mohit Patodia
 
6.applet programming in java
Deepak Sharma
 
Applet in java
Jancypriya M
 
Java applets
Khan Mac-arther
 
Applet init nd termination.59
myrajendra
 
JAVA INTRODUCTION
Prof Ansari
 
Java applet
Rohan Gajre
 
Slide8appletv2 091028110313-phpapp01
Abhishek Khune
 

Similar to Class notes(week 10) on applet programming (20)

PPTX
Applet Programming in Advance Java Programming
jayshah562401
 
PDF
UNIT-1-AJAVA.pdf
PriyanshiPrajapati27
 
PPTX
oops with java modules iii & iv.pptx
rani marri
 
DOCX
Lecture1 oopj
Dhairya Joshi
 
PDF
Java applet-basics
kanchanmahajan23
 
DOCX
Java applet-basics
kanchanmahajan23
 
PDF
Advanced programming chapter 2 - Java Applet.pdf
fikadumeuedu
 
PPTX
Applet1 (1).pptx
FahanaAbdulVahab
 
PPTX
Java applet
Elizabeth alexander
 
PPT
Java files and io streams
RubaNagarajan
 
PDF
JAVA INTRODUCTION
Prof Ansari
 
PPTX
Applets in Java
RamaPrabha24
 
PPT
Applet Architecture - Introducing Java Applets
amitksaha
 
PPTX
APPLET.pptx
SHANMUGARAJA K
 
PPT
Unit 7 Java
arnold 7490
 
PPTX
Applet in java new
Kavitha713564
 
PPTX
Applet (1)
DEEPIKA T
 
PDF
Java basics notes
sanchi Sharma
 
PDF
Java basics notes
Nexus
 
Applet Programming in Advance Java Programming
jayshah562401
 
UNIT-1-AJAVA.pdf
PriyanshiPrajapati27
 
oops with java modules iii & iv.pptx
rani marri
 
Lecture1 oopj
Dhairya Joshi
 
Java applet-basics
kanchanmahajan23
 
Java applet-basics
kanchanmahajan23
 
Advanced programming chapter 2 - Java Applet.pdf
fikadumeuedu
 
Applet1 (1).pptx
FahanaAbdulVahab
 
Java applet
Elizabeth alexander
 
Java files and io streams
RubaNagarajan
 
JAVA INTRODUCTION
Prof Ansari
 
Applets in Java
RamaPrabha24
 
Applet Architecture - Introducing Java Applets
amitksaha
 
APPLET.pptx
SHANMUGARAJA K
 
Unit 7 Java
arnold 7490
 
Applet in java new
Kavitha713564
 
Applet (1)
DEEPIKA T
 
Java basics notes
sanchi Sharma
 
Java basics notes
Nexus
 
Ad

More from Kuntal Bhowmick (20)

PDF
Multiple Choice Questions on JAVA (object oriented programming) bank 8 -- int...
Kuntal Bhowmick
 
PDF
Multiple Choice Questions on JAVA (object oriented programming) bank 7 -- abs...
Kuntal Bhowmick
 
PDF
Multiple Choice Questions on JAVA (object oriented programming) bank 6 -- inh...
Kuntal Bhowmick
 
PDF
Multiple Choice Questions on JAVA (object oriented programming) bank 5 -- mem...
Kuntal Bhowmick
 
PDF
Multiple Choice Questions on JAVA (object oriented programming) bank 4 -- loops
Kuntal Bhowmick
 
PDF
Multiple Choice Questions on JAVA (object oriented programming) bank 3 -- cla...
Kuntal Bhowmick
 
PDF
Multiple Choice Questions on JAVA (object oriented programming) bank 2 -- bas...
Kuntal Bhowmick
 
PDF
Multiple Choice Questions on JAVA (object oriented programming) bank 1 -- int...
Kuntal Bhowmick
 
PDF
Hashing notes data structures (HASHING AND HASH FUNCTIONS)
Kuntal Bhowmick
 
PPT
1. introduction to E-commerce
Kuntal Bhowmick
 
DOCX
Computer graphics question for exam solved
Kuntal Bhowmick
 
PDF
DBMS and Rdbms fundamental concepts
Kuntal Bhowmick
 
PDF
Java questions for interview
Kuntal Bhowmick
 
PDF
Java Interview Questions
Kuntal Bhowmick
 
PDF
Operating system Interview Questions
Kuntal Bhowmick
 
PDF
Computer Network Interview Questions
Kuntal Bhowmick
 
PDF
C interview questions
Kuntal Bhowmick
 
PDF
C question
Kuntal Bhowmick
 
PDF
Distributed operating systems cs704 a class test
Kuntal Bhowmick
 
DOCX
Cs291 assignment solution
Kuntal Bhowmick
 
Multiple Choice Questions on JAVA (object oriented programming) bank 8 -- int...
Kuntal Bhowmick
 
Multiple Choice Questions on JAVA (object oriented programming) bank 7 -- abs...
Kuntal Bhowmick
 
Multiple Choice Questions on JAVA (object oriented programming) bank 6 -- inh...
Kuntal Bhowmick
 
Multiple Choice Questions on JAVA (object oriented programming) bank 5 -- mem...
Kuntal Bhowmick
 
Multiple Choice Questions on JAVA (object oriented programming) bank 4 -- loops
Kuntal Bhowmick
 
Multiple Choice Questions on JAVA (object oriented programming) bank 3 -- cla...
Kuntal Bhowmick
 
Multiple Choice Questions on JAVA (object oriented programming) bank 2 -- bas...
Kuntal Bhowmick
 
Multiple Choice Questions on JAVA (object oriented programming) bank 1 -- int...
Kuntal Bhowmick
 
Hashing notes data structures (HASHING AND HASH FUNCTIONS)
Kuntal Bhowmick
 
1. introduction to E-commerce
Kuntal Bhowmick
 
Computer graphics question for exam solved
Kuntal Bhowmick
 
DBMS and Rdbms fundamental concepts
Kuntal Bhowmick
 
Java questions for interview
Kuntal Bhowmick
 
Java Interview Questions
Kuntal Bhowmick
 
Operating system Interview Questions
Kuntal Bhowmick
 
Computer Network Interview Questions
Kuntal Bhowmick
 
C interview questions
Kuntal Bhowmick
 
C question
Kuntal Bhowmick
 
Distributed operating systems cs704 a class test
Kuntal Bhowmick
 
Cs291 assignment solution
Kuntal Bhowmick
 
Ad

Recently uploaded (20)

PDF
Halide Perovskites’ Multifunctional Properties: Coordination Engineering, Coo...
TaameBerhe2
 
PPTX
265587293-NFPA 101 Life safety code-PPT-1.pptx
chandermwason
 
PDF
Electrical Engineer operation Supervisor
ssaruntatapower143
 
PPTX
Shinkawa Proposal to meet Vibration API670.pptx
AchmadBashori2
 
DOCX
CS-802 (A) BDH Lab manual IPS Academy Indore
thegodhimself05
 
PDF
Pressure Measurement training for engineers and Technicians
AIESOLUTIONS
 
PDF
Basic_Concepts_in_Clinical_Biochemistry_2018كيمياء_عملي.pdf
AdelLoin
 
PPTX
Evaluation and thermal analysis of shell and tube heat exchanger as per requi...
shahveer210504
 
DOC
MRRS Strength and Durability of Concrete
CivilMythili
 
PPTX
MATLAB : Introduction , Features , Display Windows, Syntax, Operators, Graph...
Amity University, Patna
 
PDF
Introduction to Productivity and Quality
মোঃ ফুরকান উদ্দিন জুয়েল
 
PPTX
GitOps_Without_K8s_Training_detailed git repository
DanialHabibi2
 
PDF
MAD Unit - 2 Activity and Fragment Management in Android (Diploma IT)
JappanMavani
 
PPTX
Knowledge Representation : Semantic Networks
Amity University, Patna
 
PDF
smart lot access control system with eye
rasabzahra
 
PPTX
Solar Thermal Energy System Seminar.pptx
Gpc Purapuza
 
PPTX
Presentation 2.pptx AI-powered home security systems Secure-by-design IoT fr...
SoundaryaBC2
 
PPTX
Mechanical Design of shell and tube heat exchangers as per ASME Sec VIII Divi...
shahveer210504
 
PPTX
Damage of stability of a ship and how its change .pptx
ehamadulhaque
 
PDF
Zilliz Cloud Demo for performance and scale
Zilliz
 
Halide Perovskites’ Multifunctional Properties: Coordination Engineering, Coo...
TaameBerhe2
 
265587293-NFPA 101 Life safety code-PPT-1.pptx
chandermwason
 
Electrical Engineer operation Supervisor
ssaruntatapower143
 
Shinkawa Proposal to meet Vibration API670.pptx
AchmadBashori2
 
CS-802 (A) BDH Lab manual IPS Academy Indore
thegodhimself05
 
Pressure Measurement training for engineers and Technicians
AIESOLUTIONS
 
Basic_Concepts_in_Clinical_Biochemistry_2018كيمياء_عملي.pdf
AdelLoin
 
Evaluation and thermal analysis of shell and tube heat exchanger as per requi...
shahveer210504
 
MRRS Strength and Durability of Concrete
CivilMythili
 
MATLAB : Introduction , Features , Display Windows, Syntax, Operators, Graph...
Amity University, Patna
 
Introduction to Productivity and Quality
মোঃ ফুরকান উদ্দিন জুয়েল
 
GitOps_Without_K8s_Training_detailed git repository
DanialHabibi2
 
MAD Unit - 2 Activity and Fragment Management in Android (Diploma IT)
JappanMavani
 
Knowledge Representation : Semantic Networks
Amity University, Patna
 
smart lot access control system with eye
rasabzahra
 
Solar Thermal Energy System Seminar.pptx
Gpc Purapuza
 
Presentation 2.pptx AI-powered home security systems Secure-by-design IoT fr...
SoundaryaBC2
 
Mechanical Design of shell and tube heat exchangers as per ASME Sec VIII Divi...
shahveer210504
 
Damage of stability of a ship and how its change .pptx
ehamadulhaque
 
Zilliz Cloud Demo for performance and scale
Zilliz
 

Class notes(week 10) 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); } }