1 Applications & Applets Standalone applications & Java applets Peter Mozelius DSV/UCSC.
Applets and Event Handling in Java
-
Upload
pratik-gandhi -
Category
Documents
-
view
45 -
download
0
description
Transcript of Applets and Event Handling in Java
-
5/24/2018 Applets and Event Handling in Java
1/77
Session 3 - Exception-Handling
Java Programming
11TCS Confidential
Applets and EventHandling
Java Programming
-
5/24/2018 Applets and Event Handling in Java
2/77
Session 3 - Exception-Handling
Java Programming
22TCS Confidential
AppletsApplet Basics
The Applet Architecture
Applet Initialization & Termination
Applet Restrictions
Writing a Simple AppletVisualizing How an Applet Works
-
5/24/2018 Applets and Event Handling in Java
3/77
Session 3 - Exception-Handling
Java Programming
33TCS Confidential
Applets Simple Applet Display Methods
Overriding update()
Requesting Repainting - Threadsin Applets
Using the Status WindowThe HTML APPLET Tag
Passing Parameters to Applets
-
5/24/2018 Applets and Event Handling in Java
4/77
Session 3 - Exception-Handling
Java Programming
44TCS Confidential
Applet Basics
Applet
Applets are small application thatare accessed on an internetserver, Transported over the
Internet, Automatically installedand run as part of an webdocument.
-
5/24/2018 Applets and Event Handling in Java
5/77
Session 3 - Exception-Handling
Java Programming
55TCS Confidential
Applet Basics
Component
Container
Panel
Applet
All applets
-
5/24/2018 Applets and Event Handling in Java
6/77
Session 3 - Exception-Handling
Java Programming
66TCS Confidential
Applet Basics
Run Examples
From appletviewerFrom Browser
-
5/24/2018 Applets and Event Handling in Java
7/77
Session 3 - Exception-Handling
Java Programming
77TCS Confidential
Applet Basics
Provide support for
Applet execution (start and stop)
Load and display images
load and play audio clips.
Applets must import java.applet.*and java.awt.*
Execution by Web browser or anapplet viewer provided by JDK
-
5/24/2018 Applets and Event Handling in Java
8/77
Session 3 - Exception-Handling
Java Programming
88TCS Confidential
The Applet Architecture
AWTMethods
SOPO/P
Only FewAllmain()
init()main()Begin with
AppletNormal
Class
Execution of
-
5/24/2018 Applets and Event Handling in Java
9/77
Session 3 - Exception-Handling
Java Programming
99TCS Confidential
The Applet Architecture ...
This is a crucial point.
An applet should not maintaincontrol for an extended period.
An Additional thread must be started
for repetitive task.
-
5/24/2018 Applets and Event Handling in Java
10/77
Session 3 - Exception-Handling
Java Programming
1010TCS Confidential
The Applet Architecture ...
Second
The user initiates interaction with
an applet not the other wayround.
These interactions are sent to theapplet as events to which theapplet must respond.
-
5/24/2018 Applets and Event Handling in Java
11/77
Session 3 - Exception-Handling
Java Programming
1111TCS Confidential
The Applet Architecture ...
Control applets execution by
overriding set of methods.
init
start
stop
destroy
-
5/24/2018 Applets and Event Handling in Java
12/77
Session 3 - Exception-Handling
Java Programming
1212TCS Confidential
Applet Initialization and
TerminationBegins order
init()
start()
paint()
Termination order
stop()
destroy()
-
5/24/2018 Applets and Event Handling in Java
13/77
Session 3 - Exception-Handling
Java Programming
1313TCS Confidential
Applet Initialization and
Termination init():
First method
Variables initialization
Called only once
-
5/24/2018 Applets and Event Handling in Java
14/77
Session 3 - Exception-Handling
Java Programming
1414TCS Confidential
Applet Initialization and
Termination start():
It is called after init();
Called to restart an applet
User comes back to a web page
-
5/24/2018 Applets and Event Handling in Java
15/77
Session 3 - Exception-Handling
Java Programming
1515TCS Confidential
paint():
It is called each time
Restoring the applet window
Window overwritten
When applet begins execution;
paint() has one parameter of type
Graphics.
Applet Initialization and
Termination
-
5/24/2018 Applets and Event Handling in Java
16/77
Session 3 - Exception-Handling
Java Programming
1616TCS Confidential
Applet Initialization and
Termination stop():
When a web browser leaves the
HTML document containing theapplet and goes to another page
destroy():When the environment
determines that your applet needsto be removed completely frommemory.
-
5/24/2018 Applets and Event Handling in Java
17/77
Session 3 - Exception-Handling
Java Programming
1717TCS Confidential
Applet Restrictions
Which are not enforced at compile
time.Result in run-time exception.
-
5/24/2018 Applets and Event Handling in Java
18/77
Session 3 - Exception-Handling
Java Programming
1818TCS Confidential
Applet Restrictions
Applets may not
Read, write or delete filesCreate or list directories
Check for the existence of a
file/properties
-
5/24/2018 Applets and Event Handling in Java
19/77
Session 3 - Exception-Handling
Java Programming
1919TCS Confidential
Applet Restrictions ...
Applets may not invoke a local
program
Create a network connection
Applets can read the file systemon the server it has been
downloaded from.
-
5/24/2018 Applets and Event Handling in Java
20/77
Session 3 - Exception-Handling
Java Programming
2020TCS Confidential
Applet Restrictions ...
These restrictions can be
overwhelming.
Be lifted for applets from a trusted
source.
Signing of an applet
Information is encoded that proves
that the applet can be trusted.
-
5/24/2018 Applets and Event Handling in Java
21/77
Session 3 - Exception-Handling
Java Programming
2121TCS Confidential
Demo of SampleApplet.java// Writing a Simple Appletpublic class SampleApplet extends Applet {
String msg;
// Initial settings.public void init() {msg = "In init() -- ";
setBackground(Color.cyan);setForeground(Color.red);
}public void start(){msg += "In start() -- "; }public void stop() {msg = ""; }
// Display msgpublic void paint(Graphics g) {msg += "In paint().";g.drawString(msg, 50, 150); }
}
-
5/24/2018 Applets and Event Handling in Java
22/77
Session 3 - Exception-Handling
Java Programming
2222TCS Confidential
Compiling/Running an Applet
The applet subclass must bedeclared as publ ic, because it will
be accessed by code that is outsidethe program.
Compile the program in the sameway used for other Java programs:
javac SampleApplet.java
There are three ways to run theapplet.
-
5/24/2018 Applets and Event Handling in Java
23/77
Session 3 - Exception-Handling
Java Programming
2323TCS Confidential
Compiling/Running an Applet
1.Executing within a Java-compatible Web browser:
Create file apv.html
-
5/24/2018 Applets and Event Handling in Java
24/77
Session 3 - Exception-Handling
Java Programming
2424TCS Confidential
Compiling/Running an Applet ...
2.Above html file can also beexecuted from command line as
follows at the DOS prompt:D:\suryoday> appletviewer
apv.html
-
5/24/2018 Applets and Event Handling in Java
25/77
Session 3 - Exception-Handling
Java Programming
2525TCS Confidential
Compiling/Running an Applet ...
3. Include the contents of the html fileat the head (after includes) of your
Java source code file.D:\suryoday> appletviewer
MovingBanner.javaApplet Viewer: SampleApplet.class
In init() -- In start() -- In paint()
Applet
Applet started.
-
5/24/2018 Applets and Event Handling in Java
26/77
Session 3 - Exception-Handling
Java Programming
2626TCS Confidential
Visualizing How an Applet Works
Applet CodeApplet Code
Javac compilerJavac compiler bytecode
.class file
byte code
.class fileHTML
envelope
Hello.java
Hello.class
Hello.html
Java enabled
Browser
OUTPUT
Java enabled
BrowserOUTPUT:
Hello,World!
Java Run-time
Environment
Classes.zip
Java Run-time
Environment
Classes.zip
-
5/24/2018 Applets and Event Handling in Java
27/77
Session 3 - Exception-Handling
Java Programming
2727TCS Confidential
Applet Display Methods
void drawString(String msg, int
x, int y)
Member of Graphics class.
update()or paint().
-
5/24/2018 Applets and Event Handling in Java
28/77
Session 3 - Exception-Handling
Java Programming
2828TCS Confidential
Applet Display Methods
void setBackground(Color
newColor)
void setForeground(Color newColor)
The colors can be changed during
execution.
-
5/24/2018 Applets and Event Handling in Java
29/77
Session 3 - Exception-Handling
Java Programming
2929TCS Confidential
Applet Display Methods
Current setting of
background/foreground color can
be obtained by
getBackground()/getForeground().
-
5/24/2018 Applets and Event Handling in Java
30/77
Session 3 - Exception-Handling
Java Programming
3030TCS Confidential
Overriding update()
Change default color in the Update
methods instead of Paint method.
public void update(Graphics g) {
// Redisplay the window, here. }
public void paint(Graphics g) {
update(g); }
-
5/24/2018 Applets and Event Handling in Java
31/77
Session 3 - Exception-Handling
Java Programming
3131TCS Confidential
Requesting Repainting
One of architectural constraintsimposed on applet is that
it must quickly return control to theAWT run-time system.
If the applet is displaying a movingbanner, how can it itself update the
window for its changing contents?
-
5/24/2018 Applets and Event Handling in Java
32/77
Session 3 - Exception-Handling
Java Programming
3232TCS Confidential
Requesting Repainting
It cannot create a loop inside paint()
Well, it can simply call repaint()
whenever it needs to update theinformation to be displayed.
In turn, update() is called which then
calls paint() by default.Since the scrolling of message is a
repetitive task, it should be performed by
a separate thread created by applet whenit is initialized.
-
5/24/2018 Applets and Event Handling in Java
33/77
Session 3 - Exception-Handling
Java Programming
3333TCS Confidential
Demo of MovingBanner.javaThreads in applets: This applet scrolls a
message, from right to left, across the appletswindow with the help of a thread.
import java.awt.*;import java.applet.*;
public class MovingBanner extends Applet implementsRunnable {
String msg = HELLO WORLD;Thread t = null; boolean stopFlag;
public void init() {// set colors
setBackground(Color.cyan);setForeground(Color.red);
}// end of init
-
5/24/2018 Applets and Event Handling in Java
34/77
Session 3 - Exception-Handling
Java Programming
3434TCS Confidential
MovingBanner.java ...public void start( ) { // start thread
t = new Thread(this);stopFlag = false; t.start();
} // end of startpublic void run() { char ch;
for ( ; ; ) {try {repaint();
Thread.sleep(250);
ch = msg.charAt(0);msg = msg.substring(1, msg.length());msg += ch;if (stopFlag) break;
} catch(InterruptedException e) { }}
}
-
5/24/2018 Applets and Event Handling in Java
35/77
Session 3 - Exception-Handling
Java Programming
3535TCS Confidential
MovingBanner.java ...public void stop() {
stopFlag = true; t = null;
} // end of stop
public void paint(Graphics g) {g.drawString(msg,100,100);
} // end of paint
} // end of class MovingBanner
Applet Viewer: MovingBanner.class
WORLD HELLO
Applet
Applet started.
SampleOutput:
-
5/24/2018 Applets and Event Handling in Java
36/77
Session 3 - Exception-Handling
Java Programming
3636TCS Confidential
Using the Status Window
Also output a message to status window of thebrowser or applet viewer.
By calling showStatus().
Lets write paint() again:
public void paint(Graphics g) {
g.drawString(msg,10,10);
showStatus(This is shown in statuswindow.);
}Applet Viewer: MovingBanner.class
HELLO WORLD
Applet
This is shown in status window.
-
5/24/2018 Applets and Event Handling in Java
37/77
Session 3 - Exception-Handling
Java Programming
3737TCS Confidential
The HTML APPLET Tag
The APPLET tag is used to start
an applet.
An applet viewer will execute
each APPLET tag in a separate
window
Browsers allow many applets on
a single page.
Syntax of Applet tag
-
5/24/2018 Applets and Event Handling in Java
38/77
Session 3 - Exception-Handling
Java Programming
3838TCS Confidential
The HTML APPLET Tag
[]
[< PARAM NAME = pname VALUE = pvalue >
[HTML displayed in the absence of Java]
-
5/24/2018 Applets and Event Handling in Java
39/77
Session 3 - Exception-Handling
Java Programming
3939TCS Confidential
Demo of ParamDemo.java// Passing Parameters to Appletsimport java.awt.*;
import java.applet.*;
/*
*/
public class ParamDemo extends Applet {
String fontName;
int fontSize;float leading;
-
5/24/2018 Applets and Event Handling in Java
40/77
Session 3 - Exception-Handling
Java Programming
4040TCS Confidential
ParamDemo.java ...
public void start( ) { String param;
fontName = getParameter(font);
if (fontName.equals("")) fontName=Not Found;
param = getParameter(size);try { if (param.equals("")) fontSize = 0;
else fontSize = Integer.parseInt(param);
} catch(NumberFormatException e) {fontSize=-1;}param = getParameter(leading);
try { if (param.equals("")) leading = 0;
else leading=Float.parseFloat();
} catch(NumberFormatException e) {leading=-1;}
}
-
5/24/2018 Applets and Event Handling in Java
41/77
Session 3 - Exception-Handling
Java Programming
4141TCS Confidential
ParamDemo.java ...
public void paint(Graphics g) {
g.drawString(Font name: + fontName, 40, 50);
g.drawString(Font size: + fontSize, 40, 150);
g.drawString(Leading: + leading, 40, 200);}
}Applet Viewer: ParamDemo
Font name: TimesNewRoman
Font size: 24
Leading: 25.68
Applet
Applet started.
-
5/24/2018 Applets and Event Handling in Java
42/77
Session 3 - Exception-Handling
Java Programming
4242TCS Confidential
Event Handling
Event Classes
Sources of Events
Event Listeners and Interfaces
Handling Mouse Events
Handling Keyboard events
-
5/24/2018 Applets and Event Handling in Java
43/77
Session 3 - Exception-HandlingJava Programming
4343TCS Confidential
Event Handling
Applets are event-driven programs.The most-commonly handled events
are clicking of a mouse, pressingkeyboard keys and controls likepush button. Events are supported
by java.awt.event package. In oldJava 1.0 approach, an event waspropagated up the containment
hierarchy until it was handled by acomponent, wasting valuable time.
-
5/24/2018 Applets and Event Handling in Java
44/77
Session 3 - Exception-HandlingJava Programming
4444TCS Confidential
Event Handling
The modern approach to handlingevents is based on the delegat ion
event modelin which listeners mustregister with a source in order toreceive an event notification. A
Source generates an event andsends it to one or more listeners Thelistener processes the event and
then returns.
E t H dli
-
5/24/2018 Applets and Event Handling in Java
45/77
Session 3 - Exception-HandlingJava Programming
4545TCS Confidential
Event Handling ...
An event is an object that describes astate change in a source. It can begenerated due to interaction with the
elements of a graphical user interface -pressing a button, keying a character,selecting an item in a list, and clicking
the mouse. Other events may also occurlike a timer expires, counter exceeds avalue, soft/hardware failure occurs, etc.
sourcelistener
listener
E t H dli
-
5/24/2018 Applets and Event Handling in Java
46/77
Session 3 - Exception-HandlingJava Programming
4646TCS Confidential
Event Handling ...
Source is an object that
generates an event. Sourcesmay generate more than onetype of events.
A listener is an object that isnotified when an event occurs.
E t Cl
-
5/24/2018 Applets and Event Handling in Java
47/77
Session 3 - Exception-HandlingJava Programming
4747TCS Confidential
Event Classes
The classes that represent eventsare the core of Javas event
handling mechanism. Thesuperclass of all events isEventObjectwhich is in java.util.
AWTEvent, defined within java.awt,is a subclass of EventObject. It is asuperclass of all AWT events that
are handled by the delegation eventmodel.
E t Cl
-
5/24/2018 Applets and Event Handling in Java
48/77
Session 3 - Exception-HandlingJava Programming
4848TCS Confidential
Event Classes
Package java.awt.event definesseveral types of events. Below
are enumerated the mostimportant of the event classesof this package:ActionEvent, AdjustmentEvent,ComponentEvent,
ContainerEvent, FocusEvent, InputEvent,
ItemEvent, KeyEvent, MouseEvent,TextEvent,
WindowEvent.
S f E t
-
5/24/2018 Applets and Event Handling in Java
49/77
Session 3 - Exception-HandlingJava Programming
4949TCS Confidential
Sources of Events
Button
CheckBox
Option1 Option2
Text Components
S f E t
-
5/24/2018 Applets and Event Handling in Java
50/77
Session 3 - Exception-HandlingJava Programming
5050TCS Confidential
Sources of EventsHere are some of the user interface
components that can generate events:
Event Source & Description
Button: causes action events when button ispressed.
CheckBox: causes item events when
checkbox is (de)selected.Choice : causes item events when choice is
changed.
List: causes action events when item isdouble-clicked; causes item events when itemis (de)selected.
S f E t
-
5/24/2018 Applets and Event Handling in Java
51/77
Session 3 - Exception-HandlingJava Programming
5151TCS Confidential
Sources of Events Menu Item: causes action events when
menu item is selected; causes itemevents when a checkable one is(de)selected.
Scrollbar: causes adjustment eventswhen it is manipulated.
Text Components: causes text events ona character entry.
Window: causes window events when awindow is activated, closed, deactivated,opened, quit, (de)iconified.
Event Listeners and Interfaces
-
5/24/2018 Applets and Event Handling in Java
52/77
Session 3 - Exception-HandlingJava Programming
5252TCS Confidential
Event Listeners and Interfaces
Event listeners are objects thatare notified when an event
occurs. The methods thatreceive and process events aredefined in a set of interfacesfound in java.awt.event package:
Event Listeners and Interfaces
-
5/24/2018 Applets and Event Handling in Java
53/77
Session 3 - Exception-HandlingJava Programming
5353TCS Confidential
Event Listeners and Interfaces
ActionListener
actionPerformed(ActionEvent)
AdjustmentListeneradjustmentValueChanged(AdjustmentEvent)
ComponentListenercomponentResized(ComponentEvent e)componentMoved(ComponentEvent e)componentShown(ComponentEvent e)componentHidden(ComponentEvent e)
Event Listeners and Interfaces
-
5/24/2018 Applets and Event Handling in Java
54/77
Session 3 - Exception-HandlingJava Programming
5454TCS Confidential
Event Listeners and Interfaces
MouseListenermouseClicked(MouseEvent e)mousePressed(MouseEvent e)mouseReleased(MouseEvent e)mouseEntered(MouseEvent e)
mouseExited(MouseEvent e)MouseMotionListenermouseDragged(MouseEvent e)
mouseMoved(MouseEvent e)
Event Listeners and Interfaces
-
5/24/2018 Applets and Event Handling in Java
55/77
Session 3 - Exception-HandlingJava Programming
5555TCS Confidential
Event Listeners and Interfaces
TextListenertextValueChanged(TextEvent e)
WindowListenerwindowOpened(WindowEvent e)windowClosing(WindowEvent e)
windowClosed(WindowEvent e)windowIconified(WindowEvent e)windowDeiconified(WindowEvent e)
windowActivated(WindowEvent e)windowDeactivated(WindowEvent e)
Event Listeners and Interfaces
-
5/24/2018 Applets and Event Handling in Java
56/77
Session 3 - Exception-HandlingJava Programming
5656TCS Confidential
Event Listeners and Interfaces
FocusListenerfocusGained(FocusEvent e)focusLost(FocusEvent e)
ItemListeneritemStateChanged(ItemEvent e)
KeyListenerkeyTyped(KeyEvent e)keyPressed(KeyEvent e)
keyReleased(KeyEvent e)
Demo of MouseEvents java
-
5/24/2018 Applets and Event Handling in Java
57/77
Session 3 - Exception-HandlingJava Programming
5757TCS Confidential
Demo of MouseEvents.java
Handling Mouse Events: The MouseListenerand the MouseMotionListener interfaces mustbe implemented to handle the mouse events.
import java.awt.*;import java.awt.event.*;
import java.applet.*;
public class MouseEvents extends Appletimplements
MouseListener, MouseMotionListener {
String msg = " ";int mouseX = 0, mouseY = 0; // coordinates ofmouse
public void init() {addMouseListener(this);
MouseEvents java
-
5/24/2018 Applets and Event Handling in Java
58/77
Session 3 - Exception-HandlingJava Programming
5858TCS Confidential
MouseEvents.java ...public void mouseClicked(MouseEvent me) {
msg = Mouse clicked.;
mouseX=0; mouseY=10; repaint();
} // Handling mouse clicked.
public void mouseEntered(MouseEvent me) {
msg = Mouse entered.;
mouseX=0; mouseY=10; repaint();
} // Handling mouse entered.
public boolean mouseExited(MouseEvent me){
msg = Mouse exited.;
mouseX=0; mouseY=10; repaint();
MouseEvents java
-
5/24/2018 Applets and Event Handling in Java
59/77
Session 3 - Exception-HandlingJava Programming
5959TCS Confidential
MouseEvents.java ...public void mousePressed(MouseEvent me) {
mouseX = me.getX(); mouseY = me.getY();msg = Down"; repaint( );
} // Handling mouse pressed.
public void mouseReleased(MouseEvent me) {
mouseX = me.getX(); mouseY = me.getY();
msg = Up"; repaint( );} // Handling mouse released
public void mouseMoved(MouseEvent me) {
showStatus(Moving mouse at +me.getX() + , + me.getY()); // Handlingmouse moved.}
MouseEvents java
-
5/24/2018 Applets and Event Handling in Java
60/77
Session 3 - Exception-HandlingJava Programming
6060TCS Confidential
MouseEvents.java ...
public void mouseDragged(MouseEvent me) {
mouseX = me.getX(); mouseY = me.getY();
msg = *";
showStatus(Dragging mouse at +mouseX + , + mouseY);
repaint( );
} // Handling Mose dragged
public void paint(Graphics g) {
g.drawString(msg, mouseX, mouseY);
} // Display msg in applet window at current
} // X,Y location.
Handling Keyboard events
-
5/24/2018 Applets and Event Handling in Java
61/77
Session 3 - Exception-HandlingJava Programming
6161TCS Confidential
Handling Keyboard events
On pressing a key, aKEY_PRESSED event is generated;this results in a call to keyPressed()event handler. When the key isreleased, a KEY_RELEASED event
is generated and the keyReleased()handler is executed. If a characteris generated by the keystroke, then
KEY_TYPED event is sent andkeyTyped() handler is invoked.
Handling Keyboard events
-
5/24/2018 Applets and Event Handling in Java
62/77
Session 3 - Exception-HandlingJava Programming
6262TCS Confidential
Handling Keyboard events
Thus, on each key-press at least 2and often 3 events are generated. Ifwe care about only the actualcharacters, the key press andrelease events can be ignored, but
to handle special keys (arrow /function keys), the key press eventsmust watch for them through
keyPressed() handler. Next programdemonstrates keyboard input.
Demo of SimpleKey java
-
5/24/2018 Applets and Event Handling in Java
63/77
Session 3 - Exception-HandlingJava Programming
6363TCS Confidential
Demo of SimpleKey.java// Demo of Keyboard Events
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class SimpleKey extends Appletimplements KeyListener{String msg = ;
int X = 10, Y = 20; // output coordinates
public void init() { addKeyListener(this);
requestFocus();} // request input focus
public void keyPressed(KeyEvent ke)
{ showStatus(Key Down); }
SimpleKey java
-
5/24/2018 Applets and Event Handling in Java
64/77
Session 3 - Exception-HandlingJava Programming
6464TCS Confidential
SimpleKey.java ...public void keyReleased(KeyEvent ke) {
showStatus(Key UP);
}
public void keyTyped(KeyEvent ke) {
msg += ke.getKeyChar( ); repaint( );
}
public void paint(Graphics g) {
g.drawString(msg, X, Y);
}
}
Creating animation using thread
-
5/24/2018 Applets and Event Handling in Java
65/77
Session 3 - Exception-HandlingJava Programming
6565TCS Confidential
g g
Animation is an ideal use of threadsThe program given below creates an animation
and plays a sound as well in the background
import java.awt.*;
import java.applet.AudioClip;
public class ImageAnim extendsjava.applet.Applet implements Runnable {
Image pics[]=new Image[10];
Image currimage;AudioClip c1;
Thread timage;
Creating animation using thread
-
5/24/2018 Applets and Event Handling in Java
66/77
Session 3 - Exception-HandlingJava Programming
6666TCS Confidential
public void init() {String picsource[]={"T1.gif","T2.gif","T3.gif","T4.gif",
"T5.gif","T6.gif","T7.gif","T8.gif","T9.gif", "T10.gif"};
for (int i=0;i
-
5/24/2018 Applets and Event Handling in Java
67/77
Session 3 - Exception-HandlingJava Programming
6767TCS Confidential
public void stop() {timage=null;
if (c1!=null) c1.stop();
}
public void run() {
setBackground(Color.pink);
int i=0;
Thread thisThread=Thread.currentThread();
while(timage == thisThread) {
currimage = pics[i];
repaint();
Creating animation using thread
-
5/24/2018 Applets and Event Handling in Java
68/77
Session 3 - Exception-Handling
Java Programming68
68TCS Confidential
if (c1!=null) c1.loop();try { Thread.sleep(1000);
} catch(InterruptedException e) {}
i++;
if (i==pics.length) i=0;
}
}
public void paint(Graphics g) {
if (currimage != null)
g.drawImage(currimage,10,40,this);}
}
Reducing Animation Flickering
-
5/24/2018 Applets and Event Handling in Java
69/77
Session 3 - Exception-Handling
Java Programming69
69TCS Confidential
g g
While creating animation, a call
to repaint() method is made
The repaint() method in turn
calls update() method before
calling paint() method
The update() method clears the
screen which in turn causesanimation flickering
Reducing Animation Flickering
-
5/24/2018 Applets and Event Handling in Java
70/77
Session 3 - Exception-Handling
Java Programming70
70TCS Confidential
Animation flickering can be
reduced if the update() method s
overridden in your applicationpublic void update(Graphics g) {
paint(g); }
Sometimes animation flickering
persists even after overridingupdate() method
Reducing Animation Flickering
-
5/24/2018 Applets and Event Handling in Java
71/77
Session 3 - Exception-Handling
Java Programming7171TCS Confidential
In such a case double-buffering
technique can be used that
eliminates flickering
In double-buffering, the entire
frame is first painted on a non-visible area called buffer
Then this frame is printed on thescreen
Double Buffering
-
5/24/2018 Applets and Event Handling in Java
72/77
Session 3 - Exception-Handling
Java Programming7272TCS Confidential
However, double buffering takesa lot of memory space and isnt
always the most efficient methodto reduce flickering
The following program showsthe movement of a ball along a
trajectory
Double Buffering
-
5/24/2018 Applets and Event Handling in Java
73/77
Session 3 - Exception-Handling
Java Programming7373TCS Confidential
import java.awt.*;public class BallWithBuff extends java.applet.Appletimplements Runnable {
Thread t;
int xPos=5, yPos=5;int xMove=2, yMove=4;
Double Buffering
-
5/24/2018 Applets and Event Handling in Java
74/77
Session 3 - Exception-Handling
Java Programming7474TCS Confidential
Image offscreenImage;Graphics offscreeng;
public void init() {
offscreenImage = createImage(getSize().width,
getSize().height );offscreeng=offscreenImage.getGraphics(); }
public void start() {
if (t==null) {
t=new Thread(this);t.start();
}
}
public void stop() {t=null;}
Double Buffering
-
5/24/2018 Applets and Event Handling in Java
75/77
Session 3 - Exception-Handling
Java Programming7575TCS Confidential
public void run() {Thread currThread =Thread.currentThread();
while(t == currThread) {
xPos+=xMove;yPos+=yMove;
if (yPos>=300) yMove*=-1;
if (yPos
-
5/24/2018 Applets and Event Handling in Java
76/77
Session 3 - Exception-Handling
Java Programming7676TCS Confidential
public void update(Graphics g) {paint(g);
}
public void paint(Graphics g) {
offscreeng.setColor(Color.yellow);
offscreeng.fillRect(0,0,360,351);
offscreeng.setColor(Color.red);
offscreeng.fillOval(xPos,yPos,50,50);g.drawImage(offscreenImage,0,0,this);
}
public void destroy() {offscreeng.dispose();
}
}
Summary
-
5/24/2018 Applets and Event Handling in Java
77/77
Session 3 - Exception-Handling
Java Programming7777TCS Confidential
Participants are familiarized with the:
Java threads - the Thread class, thread states,
priorities, synchronization, the Runnableinterface and creating threads.
Applet - architecture, initialization &termination, restrictions, display methods,writing simple applets, the HTML APPLET Tag,and passing parameters to applets.
Event - classes, sources of events, event
listeners and interfaces, handling mouse andkeyboard events.
Creating animation using thread