Applets and Event Handling in Java
Short Description
Applets and Event Handling In Core java...
Description
Applets and Event Handling Java Programming
Session 3 - Exception-Handling TCS Confidential
Java
1 Programming
1
Applets Applet Basics The Applet Architecture Applet Initialization & Termination Applet Restrictions Writing a Simple Applet Visualizing How an Applet Works
Session 3 - Exception-Handling TCS Confidential
Java
2 Programming
2
Applets … Simple Applet Display Methods Overriding update() Requesting Repainting - Threads in Applets Using the Status Window The HTML APPLET Tag Passing Parameters to Applets
Session 3 - Exception-Handling TCS Confidential
Java
3 Programming
3
Applet Basics Applet Applets are small application that are accessed on an internet server, Transported over the Internet, Automatically installed and run as part of an web document.
Session 3 - Exception-Handling TCS Confidential
Java
4 Programming
4
Applet Basics … Component Container Panel Applet All applets Session 3 - Exception-Handling TCS Confidential
Java
5 Programming
5
Applet Basics … Run Examples (From appletviewer (From Browser
Session 3 - Exception-Handling TCS Confidential
Java
6 Programming
6
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 an applet viewer provided by JDK Session 3 - Exception-Handling TCS Confidential
Java
7 Programming
7
The Applet Architecture Execution of Normal Class Begin with main()
Applet
main()
All
Only Few
O/P
SOP
AWT Methods
Session 3 - Exception-Handling TCS Confidential
Java
8 Programming
init()
8
The Applet Architecture ... This is a crucial point. (An applet should not maintain control for an extended period. (An Additional thread must be started for repetitive task.
Session 3 - Exception-Handling TCS Confidential
Java
9 Programming
9
The Applet Architecture ... Second (The user initiates interaction with an applet– not the other way round. (These interactions are sent to the applet as events to which the applet must respond.
Session 3 - Exception-Handling TCS Confidential
Java
10 Programming
10
The Applet Architecture ... Control applet’s execution by overriding set of methods. (init (start (stop (destroy
Session 3 - Exception-Handling TCS Confidential
Java
11 Programming
11
Applet Initialization and Termination Begins order (init() (start() (paint()
Termination order (stop() (destroy() Session 3 - Exception-Handling TCS Confidential
Java
12 Programming
12
Applet Initialization and Termination … init(): (First method (Variables initialization (Called only once
Session 3 - Exception-Handling TCS Confidential
Java
13 Programming
13
Applet Initialization and Termination … start(): (It is called after init(); (Called to restart an applet (User comes back to a web page
Session 3 - Exception-Handling TCS Confidential
Java
14 Programming
14
Applet Initialization and Termination … paint(): (It is called each time (Restoring the applet window (Window overwritten (When applet begins execution; (paint() has one parameter of type Graphics.
Session 3 - Exception-Handling TCS Confidential
Java
15 Programming
15
Applet Initialization and Termination … stop(): (When a web browser leaves the HTML document containing the applet and goes to another page
destroy(): (When the environment determines that your applet needs to be removed completely from memory. Session 3 - Exception-Handling TCS Confidential
Java
16 Programming
16
Applet Restrictions Which are not enforced at compile time. Result in run-time exception.
Session 3 - Exception-Handling TCS Confidential
Java
17 Programming
17
Applet Restrictions …
Applets may not (Read, write or delete files (Create or list directories (Check for the existence of a file/properties
Session 3 - Exception-Handling TCS Confidential
Java
18 Programming
18
Applet Restrictions ... (Applets may not invoke a local program (Create a network connection
Applets can read the file system on the server it has been downloaded from.
Session 3 - Exception-Handling TCS Confidential
Java
19 Programming
19
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. Session 3 - Exception-Handling TCS Confidential
Java
20 Programming
20
Demo of SampleApplet.java // Writing a Simple Applet public 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 msg public void paint(Graphics g) { msg += "In paint()."; g.drawString(msg, 50, 150); } Session 3 - Exception-Handling }TCS Confidential Java
21 Programming
21
Compiling/Running an Applet The applet subclass must be declared as public, because it will be accessed by code that is outside the program. Compile the program in the same way used for other Java programs: javac SampleApplet.java There are three ways to run the applet. Session 3 - Exception-Handling TCS Confidential
Java
22 Programming
22
Compiling/Running an Applet 1.Executing within a Javacompatible Web browser: Create file apv.html
Session 3 - Exception-Handling TCS Confidential
Java
23 Programming
23
Compiling/Running an Applet ... 2.Above html file can also be executed from command line as follows at the DOS prompt: D:\suryoday> appletviewer apv.html
Session 3 - Exception-Handling TCS Confidential
Java
24 Programming
24
Compiling/Running an Applet ... 3. Include the contents of the html file at the head (after includes) of your Java source code file.
D:\suryoday> appletviewer MovingBanner.java Applet Viewer: SampleApplet.class Applet In init() -- In start() -- In paint() Applet started. Session 3 - Exception-Handling TCS Confidential
Java
25 Programming
25
Visualizing How an Applet Works Applet Code
Hello.java
byte byte code code .class file .class file
Javac compiler HTML envelope
Hello.html
Java Javaenabled enabled Browser Browser OUTPUT OUTPUT: Hello,World! Session 3 - Exception-Handling TCS Confidential
Hello.class
Java
26 Programming
Java JavaRun-time Run-time Environment Environment Classes.zip Classes.zip 26
Applet Display Methods void drawString(String msg, int x, int y) Member of Graphics class. update() or paint().
Session 3 - Exception-Handling TCS Confidential
Java
27 Programming
27
Applet Display Methods … void setBackground(Color newColor) void setForeground(Color newColor) The colors can be changed during execution.
Session 3 - Exception-Handling TCS Confidential
Java
28 Programming
28
Applet Display Methods … Current setting of background/foreground color can be obtained by getBackground()/getForeground().
Session 3 - Exception-Handling TCS Confidential
Java
29 Programming
29
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); }
Session 3 - Exception-Handling TCS Confidential
Java
30 Programming
30
Requesting Repainting One of architectural constraints imposed on applet is that it must quickly return control to the AWT run-time system. If the applet is displaying a moving banner, how can it itself update the window for its changing contents? Session 3 - Exception-Handling TCS Confidential
Java
31 Programming
31
Requesting Repainting It cannot create a loop inside paint() Well, it can simply call repaint() whenever it needs to update the information 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 when it is initialized. Session 3 - Exception-Handling TCS Confidential
Java
32 Programming
32
Demo of MovingBanner.java
Threads in applets: This applet scrolls a message, from right to left, across the applet’s window with the help of a thread. import java.awt.*; import java.applet.*; public class MovingBanner extends Applet implements Runnable { String msg = “HELLO WORLD”; Thread t = null; boolean stopFlag; public void init() { // set colors setBackground(Color.cyan); setForeground(Color.red); } // end of init Session 3 - Exception-Handling TCS Confidential
Java
33 Programming
33
MovingBanner.java ... public void start( ) { // start thread t = new Thread(this); stopFlag = false; t.start(); } // end of start public 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) { } } } Session 3 - Exception-Handling TCS Confidential
Java
34 Programming
34
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
Sample Output:
Applet Viewer: MovingBanner.class Applet WORLD HELLO Applet started. Session 3 - Exception-Handling
TCS Confidential
Java
35 Programming
35
Using the Status Window Also output a message to status window of the browser or applet viewer. By calling showStatus(). Let’s write paint() again: public void paint(Graphics g) { g.drawString(msg,10,10); showStatus(“This is shown in status window.”); } Applet Viewer: MovingBanner.class Applet HELLO WORLD Session 3 - Exception-Handling This is shown in status36window. TCS Confidential Java Programming
36
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 Session 3 - Exception-Handling TCS Confidential
Java
37 Programming
37
The HTML APPLET Tag … [] [< PARAM NAME = pname VALUE = pvalue > … [HTML displayed in the absence of Java]
Session 3 - Exception-Handling TCS Confidential
Java
38 Programming
38
Demo of ParamDemo.java // Passing Parameters to Applets import java.awt.*; import java.applet.*; /* */ public class ParamDemo extends Applet { String fontName; int fontSize; float leading; Session 3 - Exception-Handling TCS Confidential
Java
39 Programming
39
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;} } Session 3 - Exception-Handling TCS Confidential
Java
40 Programming
40
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 Applet Font name: TimesNewRoman Font size: 24 Leading: 25.68 Applet started. Session 3 - Exception-Handling TCS Confidential
Java
41 Programming
41
Event Handling Event Classes Sources of Events Event Listeners and Interfaces Handling Mouse Events Handling Keyboard events
Session 3 - Exception-Handling TCS Confidential
Java
42 Programming
42
Event Handling Applets are event-driven programs. The most-commonly handled events are clicking of a mouse, pressing keyboard keys and controls like push button. Events are supported by java.awt.event package. In old Java 1.0 approach, an event was propagated up the containment hierarchy until it was handled by a component, wasting valuable time. Session 3 - Exception-Handling TCS Confidential
Java
43 Programming
43
Event Handling … The modern approach to handling events is based on the delegation event model in which listeners must register with a source in order to receive an event notification. A Source generates an event and sends it to one or more listeners The listener processes the event and then returns. Session 3 - Exception-Handling TCS Confidential
Java
44 Programming
44
Event Handling ... listener
source
listener
An event is an object that describes a state change in a source. It can be generated 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 occur like a timer expires, counter exceeds a value, soft/hardware failure occurs, etc. Session 3 - Exception-Handling TCS Confidential
Java
45 Programming
45
Event Handling ... Source is an object that generates an event. Sources may generate more than one type of events. A listener is an object that is notified when an event occurs.
Session 3 - Exception-Handling TCS Confidential
Java
46 Programming
46
Event Classes The classes that represent events are the core of Java’s event handling mechanism. The superclass of all events is EventObject which is in java.util. AWTEvent, defined within java.awt, is a subclass of EventObject. It is a superclass of all AWT events that are handled by the delegation event model. Session 3 - Exception-Handling TCS Confidential
Java
47 Programming
47
Event Classes … Package java.awt.event defines several types of events. Below are enumerated the most important of the event classes of this package: ActionEvent, AdjustmentEvent, ComponentEvent, ContainerEvent, FocusEvent, InputEvent, ItemEvent, KeyEvent, MouseEvent, TextEvent, WindowEvent. Session 3 - Exception-Handling TCS Confidential
Java
48 Programming
48
Sources of Events Button CheckBox Option1
Option2
Text Components Session 3 - Exception-Handling TCS Confidential
Java
49 Programming
49
Sources of Events… Here are some of the user interface components that can generate events: Event Source & Description Button: causes action events when button is pressed. CheckBox: causes item events when checkbox is (de)selected. Choice : causes item events when choice is changed. List: causes action events when item is double-clicked; causes item events when item is (de)selected. Session 3 - Exception-Handling TCS Confidential
Java
50 Programming
50
Sources of Events … Menu Item: causes action events when menu item is selected; causes item events when a checkable one is (de)selected. Scrollbar: causes adjustment events when it is manipulated. Text Components: causes text events on a character entry. Window: causes window events when a window is activated, closed, deactivated, opened, quit, (de)iconified. Session 3 - Exception-Handling TCS Confidential
Java
51 Programming
51
Event Listeners and Interfaces Event listeners are objects that are notified when an event occurs. The methods that receive and process events are defined in a set of interfaces found in java.awt.event package:
Session 3 - Exception-Handling TCS Confidential
Java
52 Programming
52
Event Listeners and Interfaces … ActionListener (actionPerformed(ActionEvent) AdjustmentListener
(adjustmentValueChanged(AdjustmentEv ent)
ComponentListener
(componentResized(ComponentEvent e) (componentMoved(ComponentEvent e) (componentShown(ComponentEvent e) (componentHidden(ComponentEvent e) Session 3 - Exception-Handling
TCS Confidential
Java
53 Programming
53
Event Listeners and Interfaces … MouseListener (mouseClicked(MouseEvent e) (mousePressed(MouseEvent e) (mouseReleased(MouseEvent e) (mouseEntered(MouseEvent e) (mouseExited(MouseEvent e)
MouseMotionListener
(mouseDragged(MouseEvent e) (mouseMoved(MouseEvent e) Session 3 - Exception-Handling
TCS Confidential
Java
54 Programming
54
Event Listeners and Interfaces … TextListener (textValueChanged(TextEvent e)
WindowListener
(windowOpened(WindowEvent e) (windowClosing(WindowEvent e) (windowClosed(WindowEvent e) (windowIconified(WindowEvent e) (windowDeiconified(WindowEvent e) (windowActivated(WindowEvent e) (windowDeactivated(WindowEvent e) Session 3 - Exception-Handling
TCS Confidential
Java
55 Programming
55
Event Listeners and Interfaces … FocusListener (focusGained(FocusEvent e) (focusLost(FocusEvent e)
ItemListener
(itemStateChanged(ItemEvent e)
KeyListener
(keyTyped(KeyEvent e) (keyPressed(KeyEvent e) (keyReleased(KeyEvent e) Session 3 - Exception-Handling
TCS Confidential
Java
56 Programming
56
Demo of MouseEvents.java Handling Mouse Events: The MouseListener and the MouseMotionListener interfaces must be implemented to handle the mouse events. import java.awt.*; import java.awt.event.*; import java.applet.*; public class MouseEvents extends Applet implements MouseListener, MouseMotionListener { String msg = " "; int mouseX = 0, mouseY = 0; // coordinates of mouse public void init() {addMouseListener(this); Session 3 - Exception-Handling TCS Confidential Java Programming addMouseMotionListener(this); 57
57
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;Session mouseY=10; repaint(); 3 - Exception-Handling 58 TCS Confidential Java Programming } 58
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()); // Handling mouse moved. } TCS Confidential
Session 3 - Exception-Handling Java
59 Programming
59
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. Session 3 - Exception-Handling TCS Confidential
Java
60 Programming
60
Handling Keyboard events On pressing a key, a KEY_PRESSED event is generated; this results in a call to keyPressed() event handler. When the key is released, a KEY_RELEASED event is generated and the keyReleased() handler is executed. If a character is generated by the keystroke, then KEY_TYPED event is sent and keyTyped() handler is invoked. Session 3 - Exception-Handling TCS Confidential
Java
61 Programming
61
Handling Keyboard events Thus, on each key-press at least 2 and often 3 events are generated. If we care about only the actual characters, the key press and release events can be ignored, but to handle special keys (arrow / function keys), the key press events must watch for them through keyPressed() handler. Next program demonstrates keyboard input. Session 3 - Exception-Handling TCS Confidential
Java
62 Programming
62
Demo of SimpleKey.java // Demo of Keyboard Events import java.awt.*; import java.awt.event.*; import java.applet.*; public class SimpleKey extends Applet implements 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”); } Session 3 - Exception-Handling TCS Confidential
Java
63 Programming
63
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); } } Session 3 - Exception-Handling TCS Confidential
Java
64 Programming
64
Creating animation using thread Animation is an ideal use of threads The 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 extends java.applet.Applet implements Runnable { Image pics[]=new Image[10]; Image currimage; AudioClip c1; Thread timage; Session 3 - Exception-Handling TCS Confidential
Java
65 Programming
65
Creating animation using thread …
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=300) yMove*=-1; if (yPos
View more...
Comments