Anda di halaman 1dari 26


BBA Semester III Event Handling in Java

Avi Batra, Namit Garg, Sanchit Sukhija


1. 2. 3. 4. 5.

Event Handling Adapters Types of Events Different Events Drawing Lines

3 6 7 13 24

Event Handling
Every time the user types a character or pushes a mouse button, an event occurs. Any object can be notified of the event. All it has to do is implement the appropriate

interface and be registered as an event listener on the appropriate generate event many source. Swing components of can kinds events.

Each event is represented by an object that gives information about the event and identifies the event source. Event sources are typically components, but other kinds of objects can also be event sources. Each event source can have multiple listeners registered on it. Conversely, a single listener can register with multiple event sources.

You are leaving for work in the morning and someone rings That is the an doorbell event!

In life, you encounter events that force you to suspend other activities and respond to them immediately. In Java, events represent all activity that goes on between the user and the application. Javas Abstract Windowing








programs using events. When the user interacts with a program let us say by clicking a command button, the system creates an event representing the action and delegates it to the event-handling code within the program. This code determines how to handle the event so Like the user gets the appropriate always response. foresee the




consequences of their actions. Java divides the realm of the unpredictable into exceptions and events. As we have seen, exceptions happen synchronously with a process; it is the immediate consequence of some action, such as division by 0. An event happens asynchronously, often as a result of something the user does. The Java GUI is event driven; user actions initiate events. Events are sent to a Java program by the underlying windowing system. Information about event is stored in an instance of a subclass of EventObject. Most of the events we will see are AWTEvents. Here is the hierarchy of AWTEvents -

java.lang.Object java.util.EventObject java.awt.AWTEvent java.awt.event.ActionEvent java.awt.event.AdjustmentEvent java.awt.ItemEvent java.awt.ComponentEvent java.awt.ContainerEvent java.awt.FocusEvent Lecture 16 Object-Oriented Languages and Systems 2 java.awt.InputEvent java.awt.KeyEvent java.awt.MouseEvent java.awt.PaintEvent java.awt.WindowEvent

To get an event processed, the programmer must write code to do two things: register an event listener, and implement an event handler.

Some interfaces, e.g., WindowListener, have many

methods: public void windowOpened(WindowEvent e) public void windowIconified (WindowEvent e) public void windowDeiconified (WindowEvent e) public void windowClosed (WindowEvent e) public void windowActivated (WindowEvent e) public void windowDeactivated (WindowEvent e) We could just implement all of these methods in a class like HelloWorldSwing. But, because this is tedious, the

java.awt.event package defines adapters for most of the Listeners. Adapters are classes that implement all of the methods in their corresponding interfaces, with null bodies. If the programmer only wants to define a few methods of the interface, (s) he can extend an adapter class, and override a few of its methods. However, this usually means that an object can no longer serve as a handler for its own events.

Types of events
Let us take a look at a few components and the events that they generate Button events A button generates a button event when a user clicks it with a mouse. Buttons are usually created with a oneparameter constructor. This parameter specifies the buttons label: JButton myButton = new JButton("OK");

An ActionListener receives events from the button.

When a button is pressed and released, the AWT sends an instance of ActionEvent to the button, by calling processEvent on the button. the buttons processEvent method calls

processActionEvent. processActionEvent passes the action event on to any ActionListeners that have registered an interest in events from this button. It does this by calling the ActionListeners actionPerformed method.

Keyboard events

Pressing or releasing a key generates a keyboard event. The KeyListener interface recognizes three kinds of events:

keyPressed(KeyEvent) is called when an action key is depressed. Action keys include arrow keys, function keys, Home, End, Page Up, Page Down, Num Lock, Print Screen, Scroll Lock, Caps Lock, and Pause. keyTyped(KeyEvent) is called when any other key is depressed. keyReleased(KeyEvent) is called after any key is released that has generated either of the above two events.

Four methods are useful in figuring out which key has been typed: int getKeyCode() returns the integer key code

associated with the key in this event (only for keyPressed events). char getKeyChar() returns the character associated with the key (if any). String getKeyText(int keyCode) returns a string

describing the keyCode, such as PAUSE or F1.

String getKeyModifiersText(int modifiers) returns a string describing the modifier key(s), such as Shift or Ctrl+Shift. keylistener. (Sample program to show working of Keyboard events)

public class KeyEventDemo ... implements KeyListener ... { ...//where initialization occurs: typingArea = new JTextField(20); typingArea.addKeyListener(this); ... /** Handle the key-typed event from the text field. */ public void keyTyped(KeyEvent e) { displayInfo(e, "KEY TYPED: ");

} /**Handle the key-pressed event from the text field.*/ public void keyPressed(KeyEvent e) { displayInfo(e, "KEY PRESSED: "); } /**Handle the key-released event from the text field.*/ public void keyReleased(KeyEvent e) { displayInfo(e, "KEY RELEASED: "); } ... protected void displayInfo(KeyEvent e, String s){ ... char c = e.getKeyChar(); int keyCode = e.getKeyCode(); int modifiers = e.getModifiers(); ... tmpString =KeyEvent.getKeyModifiersText(modifiers);

...//display information about the KeyEvent... } }

Item events
Several of the Swing classes implement the interface ItemSelectable, which indicates that they contain a set of items from which zero or more items may be selected. Among these classes are JButton, JCheckBox,

JRadioButton, and JComboBox. A checkbox is a box that may be selected or deselected. Any number of check boxes in a group may be selected. Radio buttons are a set of buttons of which only one can be selected at the same time. Such a set of buttons are members of the same ButtonGroup. A combo box, sometimes called a drop-down list or dropbox, allows a user to select an item from the list.








ItemEvent class contains a method getItemSelectable() to get the ItemSelectable object that generated the item event. Whenever an items state changes, the itemStateChanged() of the ItemListener class is called.

Different Events:


Object: When






application by clicking a mouse button or pressing a key an event is generated. The Operating System traps this event and the data associated with it. For example, info about time at which the event occurred, the event types (like keypress or mouse click). This data is then passed on to the application to which the event belongs. In Java, events are represented by objects, which describe the events themselves. And Java has a number of classes that describe and handle different categories of events. Event Source: An event source is the object that generated the event. Example if you click a button an

Action Event Object is generated. The object of the Action Event class contains information about the event. Event-Handler: Is a method that understands the event and processes it. The event-handler method takes the Event object as a parameter. Java uses Event-Delegation Model: with JDK1.1 onwards; you can specify the objects that are to be notified when a specific event occurs. If the event is irrelevant, it is discarded. The four main components based on this model are Event classes, Event Listeners, Explicit event handling and Adapters. Let us take a closer look at them one by one.

Event Classes: The EventObject class is at the top of the event class hierarchy. It belongs to the java.util package. While most of the other event classes are present in java.awt.event package, the getSource() method of the EventObject class returns the object that initiated the event. The getId () method returns the nature of the event. For example, if a mouse event occurs, you can find out whether the event was click, a press, a move or release from the event object.

AWT provides two conceptual types of events: Semantic and low-level events. Semantic events are defined at a higher-level to

encapsulate the semantics of user interface components model. Now let us see what the various semantic event classes are and what they generate:

An ActionEvent object is generated when a component is activated An AdjustmentEvent Object is generated when scrollbars and other adjustment elements are used. A TextEvent object is generated when text of a component is modified. An ItemEvent is generated when an item from a list, a choice or checkbox is selected. Low-Level Events is one that represents a low-level input or windows-system occurrence on a visual component on

the screen. The various low-level event classes and what they generate are as follows: A ContainerEvent Object is generated when component are added or removed from container. A ComponentEvent object is generated when a component is resized, moved etc. A FocusEvent object is generated when component receives focus for input. A KeyEvent object is generated when key on keyboard is pressed, released etc. A WindowEvent object is generated when a window activity, like maximizing or close occurs. A MouseEvent object is generated when a mouse is used. A PaintEvent object is generated when component is

painted. Event Listeners: An object delegates the task of handling an event to an event listener. When an event occurs, an event object of the appropriate type (as illustrated below) is created. This object is passed to a Listener. A listener must implement the interface that has the method for event handling. A component can have multiple listeners, and a listener can be removed using removeActionListener () method. Next question in your mind must be what is an interface? An Interface contains constant values and method declaration. The difference between classes and interface is that the methods in an interface are only declared and not implemented, that is, the methods do not have a body. What is the Need for interface? Are interfaces are used to define behavior protocols (standard behavior) that can be implemented by any class anywhere in the class hierarchy. The java.awt.event package contains definitions of all event classes and listener interface. The semantic listener interfaces define by AWT for the above mentioned semantic events are:

ActionListener AjdustmentListener ItemListener TextListener The low-level event listeners are as follows: ComponentListener ContainerListener FocusListener KeyListener MouseListener MouseMotionListener

WindowsListener. ActionEvent following using the the ActionListener usage of interface: The and



ActionListener interface in a Classic Java Application (Example I). //Save the file with file and compile it using javac, //once complied errors free execute it. Import javax.swings.*; Import java.awt.event.*; Public class MyEvent extends JFrame { JButton b1; // Main Method Public static void main (String arg[]) { MyEvent event = new MyEvent(); } //Constructor for the event derived class Public MyEvent()

{ Super(Window Title: Event Handling); b1 = new Jbutton(Click Me); //place the button object on the window getContentPane().add(center,b1); //Register the listener for the button ButtonListener listen = new ButtonListener(); b1.addActionListener(listen); //display the window in a specific size setVisible(true); setSize(200,200); } //The Listener Class Class ButtonListener implements ActionListener { //Definition for ActionPerformed() method Public void ActionPerformed(ActionEvent evt) { JButton source = (JButton)evt.getSource(); Source.setText(Button Has Been Clicked, Guru!); } }

} How The does the above begins with Application the main work? method.


An Object of the MyEvent class is created in the main method. Constructor of the MyEvent class is invoked.

Super () method calls the constructor of the base class and sets the title of the window as given.

A button object is created and placed at the center of the A Listener Object is window. created.

The addActionListener() method registers the listener object SetVisible () for method the displays the button. window.

The Application waits for the user to interact with it. When the user clicks on the button labeled Click Me: The ActionEvent event is generated. Then the ActionEvent object is created and delegated to the registered listener object for processing. The Listener object contains the actionPerformed() method which processes the ActionEvent In the actionPerformed() method, the reference to the event source is retrieved using getSource() method. The label of the button is changed to Button has been clicked, Guru! using setText() method.*

public class ClickListener extends Mouse Adapter { Public void Mouse Pressed(MouseEvent event) {

System.out.println(Mouse pressed at + , + event.getY() + ).); } }

( +event.getX()

What happens when the user pushes the mouse button? (mouseDown) What happens when the user lets go of the mouse button? (mouseUp) What happens when the mouse is just moving over the applet? (mouseMove) What happens when the mouse is dragged over the applet? (mouseDrag) What happens when the mouse enters the applet's space? (mouseEnter) What happens when the mouse leaves the applet's space? (mouseExit)

The scribbling starts at the point the mouse was pushed The scribbling stops Nothing There is a line drawn behind the mouse Nothing Nothing








MouseReleased? Among other things, each MouseEvent object contains the x and y coordinates where the event occurred. These values can be retrieved via the int getX() and int getY() methods of the mouse event. On some systems, mice have more than one button. MouseEvent inherits methods from InputEvent to allow it to distinguish among the buttons. isMetaDown() returns true when the user clicks the right button on a mouse with two or three buttons. How do you think this might be simulated on a onebutton mouse? isAltDown() returns true when the user clicks the middle button on a three-button mouse.

Drawing Lines The question now becomes: How do you draw lines on the screen? Here's a brief explanation.

The screen is represented by a special Java object called a Graphics object. You have to have a Graphics object before you can draw on anything. Graphics objects have many methods built-in, for drawing all sorts of shapes and patterns. In this exercise, there is only one method we are interested in: drawLine(). drawLine() requires 4 pieces of information to function properly: it needs to know the x coordinate and the y coordinate where the line should begin, and the x coordinate and the y coordinate where the line should stop. So to draw a line from (10,10) to (50,55), you would use the line:

g.drawLine(10, 10, 50, 55);

NOTE: this will only work, of course, if g is a Graphics object.

So, in our mouseDrag() method, we need to do the following:

We need to get the graphics object that represents the screen, and we need to draw a line on that object, from the last point the mouse was at to the point it's at now. In addition to all this, applets have a special method that is used to go find the Graphics object that represents the screen. That method is getGraphics().

Bring it all together, and your code should look like this:

public boolean mouseDrag(Event e, int x, int y) { Graphics g = getGraphics(); g.drawLine(xpoint, ypoint, x, y); }