Download - Lecture by : Mr. Tushar Gohil Lecturer,
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
1/63
AppletsApplets
Lecture By :
Mr. Tushar Gohil
Lecturer, I.T. Department
SCET,Surat.
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
2/63
IntroductionIntroduction
An Applets are small applications that areaccessed on an internet server, transportedover a internet, automatically installed &
run as a part of web document in Javacompatible web browser.
Its Execution is under the control of JVM.
An applet can react to user input &dynamically respond.
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
3/63
Applet v/s ApplicationsApplet v/s Applications
Applications are the programs that runs onyour computer , under the OS of thatcomputer.
Applets are designed to be transmittedover the internet & executed by a Java
Compatible web browser.
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
4/63
SimpleAppletSimpleApplet
import java.awt.*;
import java.applet.*;
public class SimpleApplet extends Applet {
public void paint(Graphics g) {
g.drawString("A Simple Applet", 20, 20);}
}
Applets interacts with user through the AWT, not through consolebased I/O classes. The AWT (Abstract Windows Toolkit) containssupport for window based graphical interface.
Paint() is defined by AWT. This method is called each time the appletmust be redisplay its output.
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
5/63
How to Run appletsHow to Run applets
Applets does not have main method.
Java Enable Web browser
Appletviewer
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
6/63
How to Run appletsHow to Run applets
Java Enabled Web browser
3. Create a HTML File (RunApp.html) and write this code into it
4. Open a RunApp.html or c:\>appletviewer RunApp.html
RunApp.html
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
7/63
How to Run appletsHow to Run applets
Appletviewer
3. Include this code in your applet
4. C:\>appletviewer SimpleApplet.java
import java.awt.*;
import java.applet.*;
/*
*/
public class SimpleApplet extends Applet {
public void paint(Graphics g) {
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
8/63
Applet ArchitectureApplet Architecture
Applets are event driven. An Applet waits until an eventoccurs. The AWT notifies the Applet about an event bycalling an event handler that has been provided by theApplet. Once this happens the applet must take
appropriate action and then quickly return control back toAWT.
User initiates the interaction with an applet, not the other
way around.
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
9/63
Applet SkeletonApplet Skeleton
All but most trivial applets override a set of methods thatprovides the basic mechanism by which the browser orappletviewer interfaces to the applet and controls itsexecution.
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
10/63
// An Applet skeleton.
import java.awt.*;
import java.applet.*;
/*
*/
public class AppletSkel extends Applet {
public void init() { // Called first.
// initialization}
public void start() { /* Called second, after init(). Also called whenever the applet is restarted. */
// start or resume execution
}
public void paint(Graphics g) { // Called when an applet's window must be restored.
// redisplay contents of window
}
public void stop() { // Called when the applet is stopped.
// suspends execution
}
public void destroy() { /* Called when applet is terminated. This is the last method executed. */
// perform shutdown activities
}}
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
11/63
11
The Life-Cycle of AppletThe Life-Cycle of Applet
init() Called exactly once in an applets life.
Called when applet is first loaded, which is
after object creation, e.g., when the browservisits the web page for the first time.
Used to read applet parameters, start
downloading any other images or media
files, etc.
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
12/63
12
Applet Life-Cycle (Cont.)Applet Life-Cycle (Cont.)
start() Called at least once.
Called when an applet is started or
restarted, i.e., whenever the browser visitsthe web page.
stop() Called at least once.
Called when the browser leaves the web
page.
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
13/63
13
Applet Life-Cycle (Cont.)Applet Life-Cycle (Cont.)
paint() Called each time when your applets output
needs to be redrawn.
The Graphics parameter is used wheneveroutput to the applet is required.
destroy() Called exactly once.
Called when the browser unloads the applet.
Used to perform any final clean-up.
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
14/63
14
Applet Life-Cycle (Cont.)Applet Life-Cycle (Cont.)
start
paint
stop
destroyinit
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
15/63
Skeleton.java
import java.awt.*;
import java.applet.*;
/*
*/
public class Skeleton extends Applet{
String msg;
public void init() {
msg = "Inside init( ) --";
}
public void start() {
msg += " Inside start( ) --";
}
public void paint(Graphics g) {
msg += " Inside paint( ).";
g.drawString(msg, 10, 30);
}
public void stop() {
msg += " Inside stop( ) --";
}
}
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
16/63
Applets Simple Display MethodsApplets Simple Display Methods
void drawString(String message, int x, int y)void setBackground(Color newColor)
void setForeground(Color newColor)
Color getBackground( )
Color getForeground( )
Here, newColor specifies the new color. The class Colordefines the constants shown here that can be used tospecify colors:
Color.black Color.magentaColor.blue Color.orange
Color.cyan Color.pink
Color.darkGray Color.red
Color.gray Color.white
Color.green Color.yellowColor.lightGray
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
17/63
/* A simple applet that sets the foreground and
background colors and outputs a string. */
import java.awt.*;
import java.applet.*;
/*
*/
public class Sample extends Applet{
String msg;
// set the foreground and background colors.
public void init() {setBackground(Color.cyan);
setForeground(Color.red);
msg = "Inside init( ) --";
}
// Initialize the string to be displayed.
public void start() {msg += " Inside start( ) --";
}
// Display msg in applet window.
public void paint(Graphics g) {
msg += " Inside paint( ).";
g.drawString(msg, 10, 30);
}
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
18/63
Requesting RepaintRequesting Repaint
Whenever your applet needs to update the informationdisplayed in its window, simply call the repaint() method.
It is defined by AWT. It causes the update() to be calledwhich in turn in its default implementation calls paint().
void repaint( ) void repaint(int left, int top, int width, int height)
void repaint(long maxDelay)
void repaint(long maxDelay, intx, int y, int width, int height)
maxDelay specifies the maximum number of milliseconds that can elapsebefore update( ) is called. Beware, though, If the time elapses beforeupdate( ) can be called, it isnt called.
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
19/63
Scrolling Message AppletScrolling Message Appletimport java.awt.*;
import java.applet.*;
/*
*/
public class SimpleBanner extends Applet
implements Runnable {
String msg = " A Simple Moving Banner.";Thread t = null;
boolean stopFlag;
// Set colors and initialize thread.
public void init() {
setBackground(Color.cyan);
setForeground(Color.red);
}
// Start thread
public void start() {
t = new Thread(this);
stopFlag = false;
t.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) {}
}
}
public void stop() {
stopFlag = true;
t = null;
}
public void paint(Graphics g) {
g.drawString(msg, 50, 30);
}
}
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
20/63
Using the Status BarUsing the Status BarshowStatus(String s)
import java.awt.*;
import java.applet.*;
/*
*/
public class StatusWindow extends Applet{
public void init() {
setBackground(Color.cyan);
}
public void paint(Graphics g) {
g.drawString("This is in the applet window.", 10, 20);
showStatus("This is shown in the status window.");
}
}
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
21/63
Passing Parameters to AppletPassing Parameters to Applet// Use Parameters
import java.awt.*;
import java.applet.*;
/*
*/
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
22/63
Passing Parameters to AppletPassing Parameters to Appletpublic class ParamDemo extends Applet{
String fontName;int fontSize;
float leading;
boolean active;
// Initialize the string to be displayed.
public void start() {String param;
fontName = getParameter("fontName");
param = getParameter("fontSize");
fontSize = Integer.parseInt(param);
param = getParameter("leading");leading = Float.valueOf(param).floatValue();
param = getParameter("accountEnabled");
active = Boolean.valueOf(param).booleanValue();
}
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
23/63
Passing Parameters to AppletPassing Parameters to Applet// Display parameters.
public void paint(Graphics g) {
g.drawString("Font name: " + fontName, 0, 10);
g.drawString("Font size: " + fontSize, 0, 26);
g.drawString("Leading: " + leading, 0, 42);
g.drawString("Account Active: " + active, 0, 58);
}
}
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
24/63
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
25/63
Delegation Event Model
defines standard and consistent mechanisms togenerate and process events
a source generates an event and sends it to one ormore listeners
the listener simply waits until it receives an event.
Once received, the listener processes the event andthen returns
A user interface element is able to delegate theprocessing of an event to a separate piece of code
In the delegation event model, listeners must registerwith a source in order to receive an eventnotification. so notifications are sent only to listenersthat want to receive them
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
26/63
Delegation Event Model
Events
An event is an object that describes a state changein a source.
It can be generated as a consequence of a personinteracting with the elements in a graphical userinterface
i.e. pressing button, keyboard, timer expires
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
27/63
Delegation Event Model
Events Sources
A source is an object that generates an event.
This occurs when the internal state of that objectchanges in some way. Sources may generate morethan one type of event.
A source must register listeners in order for thelisteners to receive notifications about a specific
type of event. Each type of event has its own registration method.
Here is the general form
public void addTypeListener(TypeListener el)
i.e. addKeyListener() , addMouseListner()
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
28/63
Delegation Event Model
Events Sources (Cont.)
When an event occurs, all registered listeners arenotified and receive a copy of the event object.
to remove a registration of listenerpublic void removeTypeListener(TypeListener el)
i.e. removeKeyListener() , removeMouseListner()
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
29/63
Delegation Event Model
Events Listeners
A listener is an object that is notified when anevent occurs.
It has two major requirements.
1) It must have been registered with one or moresources to receive notifications about specific typesof events.
2) it must implement methods to receive andprocess these notifications.
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
30/63
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
31/63
Delegation Event Model
Events Classes (Cont..)
EventObject (java.util)
Root Class of All the Event Classes
Constructors :
EventObject(Object src)
Mehods :Object getSource()
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
32/63
Delegation Event Model
Events Classes (Cont..)
AWTEvent
superclass of all AWT events that are handled by thedelegation event model.
Mehods :
int getID()
returns the type of event
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
33/63
Delegation Event Model
Events Classes (Cont..)
ActionEvent
It is generated when a button is pressed, a list item isdouble-clicked, or a menu item is selected
Constructors :
ActionEvent(Object src, int type, String cmd)
ActionEvent(Object src, int type, String cmd, int modifiers)
ActionEvent(Object src, int type, String cmd, long when, intmodifiers)
Integer Constants (Modifiers):
ALT_MASK,CTRL_MASK,META_MASK & SHIFT_MASK.
Type :
ACTION_PERFORMED
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
34/63
Delegation Event Model
Events Classes (Cont..)
ActionEvent (Cont..)
Methods:
String getActionCommand( )
To obtain the command name for the invoking ActionEvent object
int getModifiers( )
Returns a value that indicates which modifier keys (ALT, CTRL, META,
and/or SHIFT) were pressed when the event was generated.
long getWhen( )
Returns the time at which the event took place.
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
35/63
Delegation Event Model
Events Classes (Cont..)
AdjustmentEvent
It is generated by a scroll bar.
Constructors :
AdjustmentEvent(Adjustable src, int id, int type, int data)
Integer Constants (Type):
BLOCK_DECREMENT : clicked inside the scroll bar to decrease its value.
BLOCK_INCREMENT : clicked inside the scroll bar to increase its value.
TRACK : The slider was dragged.
UNIT_DECREMENT : The button at the end of the scroll bar was clicked todecrease its value.
UNIT_INCREMENT : The button at the end of the scroll bar was clicked toincrease its value.
ID :
ADJUSTMENT_VALUE_CHANGED
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
36/63
Delegation Event Model
EventsClasses (Cont..)
AdjustmentEvent (Cont..)
Methods:
Adjustable getAdjustable( )
returns the object that generated the event.
int getAdjustmentType( )
It returns one of the constants defined by AdjustmentEvent.
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
37/63
Delegation Event Model
Events Classes (Cont..)
ComponentEvent
It is generated when the size, position, or visibility of a component ischanged.
Constructors :ComponentEvent(Component src, int type)
Integer Constants (Type): COMPONENT_HIDDEN : The component was hidden. COMPONENT_MOVED : The component was moved. COMPONENT_RESIZED : The component was resized. COMPONENT_SHOWN : The component became visible.
Methods
Component getComponent()
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
38/63
Delegation Event Model
Events Classes (Cont..)
ContainerEventIt is generated when a component is added to or removed froma container.
Constructors :ContainerEvent(Component src, int type, Component comp)
Integer Constants (Type):
COMPONENT_ADDED COMPONENT_REMOVED
Methods
Component getContainer( )
Component getChild()
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
39/63
Delegation Event Model
Events Classes (Cont..) FocusEvent
It is generated when a component gains or loses input focus.
Constructors :
FocusEvent(Component src, int type)FocusEvent(Component src, int type, boolean temporaryFlag)
Focus Event(Component src, int type, boolean temporaryFlag, Componentother)
Integer Constants (Type): FOCUS_GAINED FOCUS_LOST
MethodsComponent getOppositeComponent( )
boolean isTemporary( )
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
40/63
Delegation Event Model
Events Classes (Cont..) InputEvent Abstract class Subclass of ComponentEvent Superclass for component input events (i.e. KeyEvent ,MouseEvent )
Integer Constants (Type):ALT_MASK ALT_DOWN_MAST
SHIFT_MASK etc.
CTRL_MASK
Methodsboolean isAltDown( )
boolean isControlDown( )
boolean isMetaDown( )
boolean isShiftDown( )
int getModifiers( )
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
41/63
Delegation Event Model
Events Classes (Cont..) KeyEvent
It is generated when keyboard input occurs.
Constructors :KeyEvent(Component src, int type, long when, int modifiers, int code)
KeyEvent(Component src, int type, long when, int modifiers, int code, char ch)
Integer Constants (Type): KEY_PRESSED
KEY_RELEASED
KEY_TYPED
Integer Constants (Code):VK_0 through VK_9 , VK_A through VK_Z
VK_ENTER VK_ESCAPE VK_CANCEL VK_UP
VK_DOWN VK_LEFT VK_RIGHT VK_PAGE_DOWN
VK_PAGE_UP VK_SHIFT VK_ALT VK_CONTROL
Methods
char getKeyChar( )
int getKeyCode()
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
42/63
Delegation Event Model
Events Classes (Cont..) MouseEvent
Constructors :MouseEvent(Component src, int type, long when, int modifiers, intx, inty, int clicks, boolean triggersPopup)
Integer Constants (Type): MOUSE_CLICKED The user clicked the mouse.
MOUSE_DRAGGED The user dragged the mouse.
MOUSE_ENTERED The mouse entered a component.
MOUSE_EXITED The mouse exited from a component.
MOUSE_MOVED The mouse moved.
MOUSE_PRESSED The mouse was pressed.
MOUSE_RELEASED The mouse was released. MOUSE_WHEEL The mouse wheel was moved
Methods
int getX( )
int getY( )
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
43/63
Delegation Event Model
Events Classes (Cont..) MouseWheelEvent
Constructors :
MouseWheelEvent(Component src, int type, long when, int modifiers, intx, int y, int clicks, boolean triggersPopup, int scrollHow, int amount, intcount)
Integer Constants (Type): WHEEL_BLOCK_SCROLL A page-up or page-down scroll event occurred. WHEEL_UNIT_SCROLL A line-up or line-down scroll event occurred.
Methodsint getScrollType( )
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
44/63
Delegation Event Model
Events Classes (Cont..) WindowEvent
Constructors :WindowEvent(Window src, int type)
Integer Constants (Type):
WINDOW_ACTIVATED The window was activated. WINDOW_CLOSED The window has been closed.
WINDOW_CLOSING The user requested that the window be closed. WINDOW_DEACTIVATED The window was deactivated. WINDOW_DEICONIFIED The window was deiconified. WINDOW_GAINED_FOCUS The window gained input focus. WINDOW_ICONIFIED The window was iconified. WINDOW_LOST_FOCUS The window lost input focus.
WINDOW_OPENED The window was opened.
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
45/63
| Some event classes of package| Some event classes of package java.awt.eventjava.awt.event ..
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
46/63
Delegation Event Model
Events Listeners
Listeners are created by implementing one ormore of the interfaces defined by the
java.awt.event package.
When an event occurs, the event source invokesthe appropriate method defined by the listenerand provides an event object as its argument.
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
47/63
Delegation Event Model
Events Classes (Cont..)
ActionListener Interface
This interface defines the actionPerformed( ) methodthat is invoked when an action event occurs.
Methods :
void actionPerformed(ActionEvent ae)
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
48/63
Delegation Event Model
Events Classes (Cont..)
AdjustmentListener Interface
Methods :
void adjustmentValueChanged(AdjustmentEvent ae)
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
49/63
Delegation Event Model
Events Classes (Cont..) ComponentListener Interface
Methods :
void componentResized(ComponentEvent ce)
void componentMoved(ComponentEvent ce)
void componentShown(ComponentEvent ce)
void componentHidden(ComponentEvent ce)
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
50/63
Delegation Event Model
Events Classes (Cont..) FocusListener Interface
Methods :
void focusGained(FocusEvent fe)
void focusLost(FocusEvent fe)
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
51/63
Delegation Event Model
Events Classes (Cont..) KeyListener Interface
Methods :
void keyPressed(KeyEvent ke)
void keyReleased(KeyEvent ke)
void keyTyped(KeyEvent ke)
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
52/63
Delegation Event Model
Events Classes (Cont..) MouseListener Interface
Methods :
void mouseClicked(MouseEvent me)
void mouseEntered(MouseEvent me)
void mouseExited(MouseEvent me)
void mousePressed(MouseEvent me)void mouseReleased(MouseEvent me)
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
53/63
Delegation Event Model
Events Classes (Cont..) MouseMotionListener Interface
Methods :
void mouseDragged(MouseEvent me)
void mouseMoved(MouseEvent me)
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
54/63
54 Some common event-listener interfacesSome common event-listener interfaces
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
55/63
Using Delegation Event Model
Just follow these two steps:
3. Implement the appropriate interface in the listenerso that it will receive the type of event desired.
5. Implement code to register and unregister (ifnecessary) the listener as a recipient for the eventnotifications.
Handling Mouse Events
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
56/63
Handling Mouse Eventspublic class MouseEvents extends Applet
implements MouseListener, MouseMotionListener {
String msg = "";
int mouseX = 0, mouseY = 0;public void init() {
addMouseListener(this);
addMouseMotionListener(this);
}
// Display msg in applet window at current X,Ylocation.
public void paint(Graphics g) {
g.drawString(msg, mouseX, mouseY);
}
// Handle mouse clicked.
public void mouseClicked(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse clicked.";
repaint();
}
// Handle mouse entered.
public void mouseEntered(MouseEvent me) {
mouseX = 0;
mouseY = 10;msg = "Mouse entered.";
repaint();
}
// Handle mouse exited.
public void mouseExited(MouseEvent me) {mouseX = 0;
mouseY = 10;
msg = "Mouse exited.";
repaint();
}
public void mousePressed(MouseEvent me) {
mouseX = me.getX();
mouseY = me.getY();
msg = "Down";
repaint();
}
Handling Mouse Events
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
57/63
Handling Mouse Events// Handle button released.
public void mouseReleased(MouseEvent me) {
// save coordinates
mouseX = me.getX();mouseY = me.getY();
msg = "Up";
repaint();
}
// Handle mouse dragged.
public void mouseDragged(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "*";
showStatus("Dragging mouse at " + mouseX + ", " + mouseY);
repaint();
}
// Handle mouse moved.
public void mouseMoved(MouseEvent me) {
// show status
showStatus("Moving mouse at " + me.getX() + ", " + me.getY());
}
}
Handling Key Events
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
58/63
Handling Key Eventspublic class SimpleKey extends Applet
implements KeyListener {
String msg = "";
int X = 10, Y = 20; // output coordinates
public void init() {
addKeyListener(this);
}
public void keyPressed(KeyEvent ke) {
showStatus("Key Down");
}public void keyReleased(KeyEvent ke) {
showStatus("Key Up");
}
public void keyTyped(KeyEvent ke) {
msg += ke.getKeyChar();
repaint();}
// Display keystrokes.
public void paint(Graphics g) {
g.drawString(msg, X, Y);
}
}
Adapter Classes
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
59/63
Adapter Classes
An Adapter class provides an empty implementation of all
methods in an event listener interface. Adapter Classes are useful when you want to receive and
process only some of the events that are handled by aparticular interface.
You can define a new class to act as a event listener byextending one of the adapter classes and implementing only
those methods in which you are interested.
public class AdapterDemo extends Applet {
public void init() {
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
60/63
p () {
addMouseListener(new MyMouseAdapter(this));
addMouseMotionListener(new MyMouseMotionAdapter(this));
}
}
class MyMouseAdapter extends MouseAdapter {
AdapterDemo adapterDemo;
public MyMouseAdapter(AdapterDemo adapterDemo) {
this.adapterDemo = adapterDemo;
}
public void mouseClicked(MouseEvent me) {
adapterDemo.showStatus("Mouse clicked");
}
}
class MyMouseMotionAdapter extends MouseMotionAdapter {
AdapterDemo adapterDemo;
public MyMouseMotionAdapter(AdapterDemo adapterDemo) {
this.adapterDemo = adapterDemo;
}
public void mouseDragged(MouseEvent me) {
adapterDemo.showStatus("Mouse dragged");
}}
Inner Classes
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
61/63
Inner Classes
Inner Classes are a classes which are defined within otherclass.
class MyMouseAdapter extends MouseAdapter {
MousePressedDemo mousePressedDemo;
public MyMouseAdapter(MousePressedDemo mousePressedDemo) {
this.mousePressedDemo = mousePressedDemo;
}public void mousePressed(MouseEvent me) {
mousePressedDemo.showStatus("Mouse Pressed.");
}
}
public class MousePressedDemo extends Applet {public void init() {
addMouseListener(new MyMouseAdapter(this));
}
}
Inner Classes
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
62/63
Inner Classes
public class InnerClassDemo extends Applet {
public void init() {
addMouseListener(new MyMouseAdapter());
}
class MyMouseAdapter extends MouseAdapter {
public void mousePressed(MouseEvent me) {
showStatus("Mouse Pressed");
}
}
}
Anonymous Inner Classes
-
8/14/2019 Lecture by : Mr. Tushar Gohil Lecturer,
63/63
Anonymous Inner Classes
public class AIDemo extends Applet {public void init() {
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
showStatus("Mouse Pressed");
}});
}
}
An Anonymous class is one that is not assigned a name. The syntax new MouseAdapter( ) { ... } indicates to the
compiler that the code between the braces defines ananonymous inner class. Furthermore, that class extendsMouseAdapter. This new class is not named, but it isautomatically instantiated when this expression is executed