Sei sulla pagina 1di 14

QUESTIONS FROM PREVIOUS PAPERS

UNIT-6
1. Mention the keyboard events.
2. What is Event Delegation model?
3. List out mouse events in the MouseEvent class.
4. What is the use of adapter classes?
5. What are the methods supported by key listener interface and mouse listener
interface?
6. Discuss the following Event Listener Interfaces and also discuss various
methods declared in it.
i)WindowFocusListener ii) TextListener iii) KeyListener
7. Differences between applets and application?
8. What is an Applet?. Write about Life Cycle of an Applet.
9. Write a program to create an applet.
10.What are the uses of applet?
11.Write the Java code for an Applet Skeleton and explain it.
12.How can the parameters be passed to an applet?

The Delegation Event Model


 It defines standard and consistent mechanisms to generate and process events.
 In this model, a source generates an event and sends it to one or more listeners.
 The listener simply waits until it receives an event. Once received, the listener processes
the event and then returns.
 Listeners are created by implementing one or more of the interfaces defined by the
java.awt.event package.
 When an event occurs, the event source invokes the appropriate method defined by the
listener and provides an event object as its argument.
 In the delegation event model, listeners must register with a source in order to receive
an event notification.

1
Events
 Events are supported by the java.awt.event package.
 An event is an object that describes a state change in a source.
 Events can be generated as a consequence of a person interacting with elements in a
graphical user interface.
 Events may also occur that are not directly caused by interactions with a user interface.
For example, an event may be generated
 when a timer expires,
 a counter exceeds a value,
 a software or hardware failure occurs.

Event Sources
 A source is an object that generates an event. This occurs when the internal state of that
object changes in some way.
 Sources may generate more than one type of event.
 A source must register listeners in order for the listeners 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)

2
Here, Type is the name of the event and el is a reference to the event listener.
For example, the method that registers a keyboard event listener is called
addKeyListener( ).

Event Listeners :

 A listener is an object that is notified when an event occurs.


 It has two major requirements.
First, it must have been registered with one or more sources to receive notifications
about specific types of events.
Second, it must implement methods to receive and process these notifications.
 For example, the MouseMotionListener interface defines two methods to
receive notifications when the mouse is dragged or moved.
 Any object may receive and process one or both of these events if it provides an
implementation of this interface.

Event Classes:

 EventObject is a superclass of all events which is defined in java.util package.


 AWTEvent is a superclass of all AWT events that are handled by the delegation event
model which is defined in java.awt package.
The following are the main event classes in java.awt.event package.

Event Class Description


ActionEvent Generated when a button is pressed, a list item is double-clicked,
or a menu item is selected.
MouseEvent Generated when the mouse is dragged, moved, clicked, pressed, or
released; also generated when the mouse enters or exits a component.
KeyEvent Generated when the key is pressed , key is released, or key is typed.
TextEvent Generated when the value of a text area or text field is changed.
MouseWheelEvent Generated when the mouse wheel is moved.
WindowEvent Generated when a window is activated, deactivated,
deiconified, iconified, opened, closing, closed.
ItemEvent Generated when a check box or list item is clicked; also occurs when a
choice selection is made or a checkable menu item is selected or
deselected.
FocusEvent Generated when a component gains or loses keyboard focus.
AdjustmentEvent Generated when a scroll bar is manipulated.
ContainerEvent Generated when a component is added to or removed from a container.

The ActionEvent Class :


 You can obtain the command name for the invoking ActionEvent object by using
the
String getActionCommand() method.
 The getWhen( ) returns the time at which the event took place.

3
The KeyEvent Class:

 int getKeyChar( ) which returns the character that was entered, and int
getKeyCode( ) which returns the key code.
 It defines many integer constants:
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

The MouseEvent Class:

 int getX( ) int getY( )


 The int getClickCount( ) method obtains the number of mouse clicks for this
event.

The ItemEvent Class:

 The int getStateChange() method returns the state change (i.e., SELECTED or
DESELECTED) for the event.
 The Object getItem( ) method can be used to obtain a reference to the item that
generated an event.

The following table lists some of the user interface components that can generate the events.

Event Source Description

Button Generates action events when the button is pressed.

Choice Generates item events when the choice is changed.

List Generates action events when an item is double-clicked; generates


item events when an item is selected or deselected.
Window Generates window events when a window is activated, closed,
deactivated, deiconified, iconified, opened, or quit.
Menu Item Generates action events when a menu item is selected; generates
item events when a checkable menu item is selected or deselected.
Scrollbar Generates adjustment events when the scroll bar is manipulated.
Text components Generates text events when the user enters a character.

Checkbox Generates item events when the check box is selected or deselected.

4
Listener Interfaces:

Interface Description

ActionListener Defines one method to receive action events.


AdjustmentListener Defines one method to receive adjustment events.
ComponentListener Defines four methods to recognize when a component is
hidden, moved, resized, or shown.
ContainerListener Defines two methods to recognize when a component is
added to or removed from a container.
FocusListener Defines two methods to recognize when a component
gains or loses keyboard focus.
ItemListener Defines one method to recognize when the state of an
item changes.
KeyListener Defines three methods to recognize when a key is pressed,
released, or typed.

MouseListener Defines five methods to recognize when the mouse is


clicked, enters a component, exits a component, is
pressed, or is released.
MouseMotionListener Defines two methods to recognize when the
mouse is dragged or moved.
MouseWheelListener Defines one method to recognize when the
mouse wheel is moved.
TextListener Defines one method to recognize when a text
value changes.
WindowFocusListener Defines two methods to recognize when a
window gains or loses input focus.
WindowListener Defines seven methods to recognize when a
window is activated, closed, deactivated,
deiconified, iconified, opened, or quit.

Listener Interfaces and associated Event Classes

ActionEvent ActionListener
MouseEvent MouseListener
MouseMotionListener
KeyEvent KeyListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
ItemEvent ItemListener
TextEvent TextListener
WindowEvent WindowListener

5
The ActionListener Interface
This interface defines the actionPerformed() method that is invoked when an
action event occurs. Its general form is shown here:
void actionPerformed(ActionEvent ae)
The AdjustmentListener Interface
void adjustmentValueChanged(AdjustmentEvent ae)
The ComponentListener Interface
This interface defines four methods that are invoked when a component is resized,
moved, shown, or hidden.
void componentResized(ComponentEvent ce)
void componentMoved(ComponentEvent ce)
void componentShown(ComponentEvent ce)
void componentHidden(ComponentEvent ce)
The ItemListener Interface
void itemStateChanged(ItemEvent ie)

The ContainerListener Interface


When a component is added or removed to and from a container the following methods
are invoked.
void componentAdded(ContainerEvent ce)
void componentRemoved(ContainerEvent ce)
The KeyListener Interface
void keyPressed(KeyEvent ke)
void keyReleased(KeyEvent ke)
void keyTyped(KeyEvent ke)
The MouseListener Interface
void mouseClicked(MouseEvent me)
void mouseEntered(MouseEvent me)
void mouseExited(MouseEvent me)
void mousePressed(MouseEvent me)
void mouseReleased(MouseEvent me)

The MouseMotionListener Interface


void mouseDragged(MouseEvent me)
void mouseMoved(MouseEvent me)
The WindowListener Interface
void windowActivated(WindowEvent we)
void windowClosed(WindowEvent we)
void windowClosing(WindowEvent we)
void windowDeactivated(WindowEvent we)
void windowDeiconified(WindowEvent we)
void windowIconified(WindowEvent we)
void windowOpened(WindowEvent we)
The MouseWheelListener Interface
void mouseWheelMoved(MouseWheelEvent mwe)

6
The TextListener Interface
void textChanged(TextEvent te)

Adapter Classes:

 Java provides a special feature, called an adapter class, that can simplify the creation of event
handlers in certain situations.
 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 a particular event listener interface.
 You can define a new class to act as an event listener by extending one of the adapter classes and
implementing only those events in which you are interested.

 lists the commonly used adapter classes in java.awt.event and


corresponding interfaces.

Adapter Class Listener Interface


KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
WindowAdapter WindowListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
FocusAdapter FocusListener

// Demonstrate the mouse event handlers.


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code="MouseEvents" width=300 height=100></applet>*/

public class MouseEvents extends Applet implements MouseListener,


MouseMotionListener,MouseWheelListener {
String msg = "";
int mouseX = 0, mouseY = 0; // coordinates of mouse

public void init() {


addMouseListener(this);
addMouseMotionListener(this);
addMouseWheelListener(this);
}

// Handle mouse clicked.


public void mouseClicked(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;

7
msg = "Mouse clicked.";
repaint();
}

// Handle mouse entered.


public void mouseEntered(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse entered.";
repaint();
}

// Handle mouse exited.


public void mouseExited(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse exited.";
repaint();
}

// Handle button pressed.


public void mousePressed(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Down";
repaint();
}

// 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.

8
public void mouseMoved(MouseEvent me) {
// show status
showStatus("Moving mouse at " + me.getX() + ", " + me.getY());
}

// Handle mouse wheel moved.


public void mouseWheelMoved(MouseWheelEvent me) {
// show status
showStatus("Mouse Wheel Moving at " + me.getX() + ", " + me.getY());
}

// Display msg in applet window at current X,Y location.


public void paint(Graphics g) {
g.drawString(msg, mouseX, mouseY);
}
}

// Demonstrate some virtual key codes.


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="KeyEvents" width=300 height=100></applet>*/
public class KeyEvents 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");
int key = ke.getKeyCode();
switch(key) {
case KeyEvent.VK_PAGE_DOWN:
msg += "<PgDn>";
break;
case KeyEvent.VK_PAGE_UP:
msg += "<PgUp>";
break;
case KeyEvent.VK_LEFT:
msg += "<Left Arrow>";
break;
case KeyEvent.VK_UP:
msg += "<Up Arrow>";
break;

9
case KeyEvent.VK_DOWN:
msg += "<Down Arrow>";
break;
case KeyEvent.VK_9:
msg += "<Digit 9>";
break;
case KeyEvent.VK_RIGHT:
msg += "<Right Arrow>";
break;
}
repaint();
}

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);
}
}

What is an applet?
Applet: A small Java program that can be inserted into a web page and run by loading that page in a
browser.
An applet is a special kind of Java program that is designed to be transmitted over the Internet and
automatically executed by a Java- compatible web browser.
Applets are small applications that are accessed on an Internet server, transported over the Internet,
automatically installed, and run as part of a web document.
Applet classes in Java
java.lang.Object
java.awt.Component
java.awt.Container
java.awt.Panel
java.applet.Applet
javax.swing.JApplet

10
How Applets Differ from Applications
Although both the Applets and stand-alone applications are Java programs, there are certain restrictions
are imposed on Applets due to security concerns:
– Applets don’t use the main() method, but when they are loaded, automatically call certain
methods (init, start, paint, stop, destroy).
– They are embedded inside a web page and executed in browsers.
– Takes input through Graphical User Input ( GUI ).
– They cannot read from or write to the files on local computer.
– They cannot run any programs from the local computer.
– They are restricted from using libraries from other languages.
The above restrictions ensures that an Applet cannot do any damage to the local system.
1. Applets can be embedded in HTML pages and downloaded over the Internet whereas
Applications have no special support in HTML for embedding or downloading.
2. Applets can only be executed inside a java compatible web browser or appletviewer whereas
Applications are executed at command line by java.
3. After an applet arrives on the client, it has limited access to resources on local computer.
Applications have no restriction to access resources.
4. Applets don’t have the main() method as in applications. Instead they operate on an entirely
different mechanism where they are initialized by init(),started by start(),stopped by stop() or
destroyed by destroy().
5. A Java Applet is made up of at least one public class that has to be subclasses from
java.applet.Applet. Whereas, A Java application is made up of a main() method declared as public
static void that accepts a string array argument, along with any other classes that main() calls.

11
It is important to understand the order in which these methods are called.
 When an applet is started , the following sequence of method calls takes place:
1. init( )
2. start( )
3. paint( )
 When an applet is terminated, the following sequence of method calls takes place:
1. stop( )
2. destroy( )
Initialisation
 The init( ) method is the first method to be called.
 This is where you should initialize variables.
This method is called only once during the run time of your applet.
Running – more than once
The start( ) method is called after init( ).
It is also called to restart an applet after it has been stopped.
It is called each time an applet’s HTML document is displayed on screen.
So, if a user leaves a web page and comes back, the applet resumes execution at start( ).
Display – more than once
 paint() happens immediately after the applet enters into the running state.
It is responsible for displaying output.
 paint( ) is also called when the applet begins execution.
 The paint( ) method is called each time your applet’s output must be redrawn.
 The paint( ) method has one parameter of type Graphics.
Idle
 The stop( ) method is called when a web browser leaves the HTML document containing
the applet—when it goes to another page.

12
Dead/Destroyed State – only once
 The destroy( ) method is called when the environment determines that your applet needs
to be removed completely from memory.
 At this point, you should free up any resources the applet may be using. The stop( )
method is always called before destroy( ).

Structure of an applet:

// An Applet AppletStructure
import java.awt.*;
import java.applet.*;
/* <applet code="AppletStructure" width=300 height=100> </applet> */
public class AppletStructure extends Applet {
// Called first.
public void init() {
// initialization
}
/* Called second, after init(). Also called whenever the applet is restarted. */
public void start() {
// start or resume execution
}
// Called when the applet is stopped.
public void stop() {
// suspends execution
}
/* Called when applet is terminated. This is the last method executed. */
public void destroy() {
// perform shutdown activities
}
// Called whenever an applet's output must be redisplayed.
public void paint(Graphics g) {
// redisplay contents of window
}
}
Building Applet Code: An Example
import java.awt.*;
import java.applet.Applet;
/* <applet code="SimpleApplet" width=300 height=50> </applet> */
public class SimpleApplet extends Applet
{
public void paint(Graphics g)
{
g.drawString ("A Simple Applet",100, 100);
}
}

 Begins with two import classes.


 java.awt.* -- required for GUI

13
 java.applet.* -- every applet you create must be a subclass of Applet,
which is in java.applet package.
 The class should start with public, because is accessed from outside.
 Applets do not begin execution at main().
 An applet begins its execution when the name of its class is passed to an applet viewer or to a
java compatible browser.
 Compile the applet in the same way that we have been compiling programs.
 Running an applet involves a different process.
Executing in a web browser.
 To execute an applet in a web browser, you need to write a short HTML file that contains a tag (
Applet ) that loads the applet.
HTML file that contains a SimpleApplet
<APPLET code=“SimpleApplet“ width=400 height=300>
</APPLET>
 Save the file with .html extension (Example: Simple.html)
 After you create this file, open your browser and then load this file, which causes SimpleApplet
to be executed.
 width and height specify the dimensions of the display used by the applet.
There are two ways
1. Use earlier html page, which contains applet tag, then execute by using following
command.
C:\>appletviewer SimpleApplet.html
2. Include a comment at the beginning of your source code file that
contains the applet tag, then start applet viewer with your java source
code file. C:\>appletviewer SimpleApplet.java
 Four of these methods init(), start(), stop(), and destroy() are defined by Applet.
 Another, paint() is defined by the AWT Component class.
 Although the above program does not do anything, it can be compiled and run.

Passing Parameters to Applet


 The APPLET tag in HTML allows you to pass parameters to your applet.
 To retrieve a parameter, use the getParameter( ) method.
 It returns the value of the specified parameter in the form of a String object.

import java.applet.Applet;
import java.awt.*;
/* <APPLET CODE="HelloAppletMsg" width=500 height=400>
<PARAM NAME="Greetings" VALUE="Hello Srinivas, How are you?">
</APPLET> */
public class HelloAppletMsg extends Applet {
String msg;
public void init()
{
msg = getParameter("Greetings");
if( msg == null)
msg = "Hello";
}
public void paint(Graphics g) {
g.drawString (msg,10, 100);
}
}

14

Potrebbero piacerti anche