Jan. 20041 Event Handling -1.1 Yangjun Chen Dept. Business Computing University of Winnipeg.

Slides:



Advertisements
Similar presentations
Event handling and listeners What is an event? user actions and context event sources and listeners Why should my programs be event- driven? User interaction.
Advertisements

1 Graphical User Interface (GUI) Applications Abstract Windowing Toolkit (AWT) Events Handling Applets.
Java GUI building with the AWT. AWT (Abstract Window Toolkit) Present in all Java implementations Described in (almost) every Java textbook Adequate for.
Programming in Java; Instructor:John Punin Graphics and Graphical User Interfaces1 Programming in Java Graphics and Graphical User Interfaces.
 Specifies a set of methods (i.e., method headings) that any class that implements that interface must have.  An interface is a type (but is not a class).
Mouse Listeners We continue our examination of GUIs by looking at how to interact with the mouse –Just as Java creates Events when the user interacts with.
CSE 341, S. Tanimoto Java-PolyDraw- 1 A Java Case Study: An Applet for Drawing Polygons Motivation -- See a number of AWT features integrated. Get ideas.
TCU CoSc Programming with Java Handling Events.
Event-Driven Programming You might have realized in creating a GUI and clicking on the JButtons that nothing happens Clicking on a JButton causes the JVM.
Jan Event Handling Yangjun Chen Dept. Business Computing University of Winnipeg.
Events and the AWT The objectives of this chapter are: To understand the principles of the Java 1.1 event model To understand how the event model is used.
Event Handling. In this class we will cover: Basics of event handling The AWT event hierarchy Semantic and low-level events in the AWT.
Event Handling Events and Listeners Timers and Animation.
Lecture 24 Applets. Introduction to Applets Applets should NOT have main method but rather init, stop, paint etc They should be run through javac compiler.
Event Handling n Events: an event is an object that describes a state change in a source. n Event Sources: A source is an object that generates an event.
1 Gui Programming (Part I) Graphical User Interfaces (Part I) l Introduction to events. l A Brief history. l Event sources and listeners. l The delegation.
Event Handling. In this class we will cover: Keyboard Events Mouse Events Focus Events Action Interface Multicasting.
PROGRAMMING REVIEW Lab 2 EECS 448 Dr Fengjun Li and Meenakshi Mishra.
28-Aug-15 Air Force Institute of Technology Electrical and Computer Engineering Object-Oriented Programming Design Topic : Event Handling – GUI Part II.
Chapter 11 Java AWT Part I: Mouse Events (Optional) Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition) by S.N. Kamin,
Graphical User Interface CSI 1101 N. El Kadri. Plan - agenda Graphical components Model-View-Controller Observer/Observable.
Java Programming: Guided Learning with Early Objects
Cs884(Prasad)java12AWT1 Abstract Windowing Toolkit Support for Graphical User Interface (Event-driven programming)
7/3/00SEM107- © Kamin & ReddyClass 11 - Events - 1 Class 11 - Events r A couple of odds & ends m Component sizes  switch statement r Event types r Catching.
Graphical User Interface Components: Part 1 Chapter 11.
– Advanced Programming P ROGRAMMING IN Lecture 21 Introduction to Swing.
1 Outline 1 Introduction 2 Overview of Swing Components 3 JLabel 4 Event Handling 5 TextFields 6 How Event Handling Works 7 JButton 8 JCheckBox and JRadioButton.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
1 Unit 5 GUI Aum Amriteshwaryai Namah. 2 Overview Shall learn how to reuse the graphics classes provided by Java for constructing Graphical User Interface.
MSc Workshop - © S. Kamin, U.Reddy Lect 4 - Events - 1 Lecture 4 – Event Handling r Painting r Event types r Catching different event types.
12/5/00SEM107, Kamin & ReddyReview - 34 Events Event types Catching different event types Getting information from components and events Distinguishing.
Omer Boyaci.  GUIs are event driven.  When the user interacts with a GUI component, the interaction—known as an event—drives the program to perform.
Pravin Yannawar, DOCS, NMU Jalgaon. Basic Java : Event handling in AWT and Swing 2 Objectives of This Session Explain the Event handling mechanism & demonstrate.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 21.1 Test-Driving the Painter Application.
UID – Event Handling and Listeners Boriana Koleva
Event Handling. 2 GUIs are event driven –Generate events when user interacts with GUI e.g., moving mouse, pressing button, typing in text field, etc.
Interactive Programs Java API. Terminology Event—an action or occurrence, not part of a program, detected by the program. Events can be Event—an action.
Universidad Nacional de Colombia Facultad de Ingeniería Departamento de Sistemas ertificación en AVA.
CMSC 341 Making Java GUIs Functional. 09/29/2007 CMSC 341 Events 2 More on Swing Great Swing demo at /demos/jfc/SwingSet2/SwingSet2Plugin.html.
Object Oriented Programming.  Interface  Event Handling.
Event Handling. The signals that a program receives from the operating system as a result of the actions are called events. A window based program is.
Agenda Introduction. Event Model. Creating GUI Application. Event Examples.
Index Event Handling Events Event Source Event Listener Event Classes Action Event Class Adjustment event Class Event Source Event Listener Interface Using.
(c) by Elizabeth Sugar Boese.1 Chapter 6 Events - Lecture Slides.
Events in JAVA Needed for Applets and GUI based programs. Applet uses GUI to interact with user. Most of the events are generated by Mouse, Keyboard.
Events (Chapter 11) Java Certification Study Group January 25, 1999 Mark Roth.
Chapter 6: Events in Java 1.0 Model –Event class –selecting component to handle –handleEvent method –helper methods (action, keyUp, mouseUp, etc.) 1.1.
What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event.
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
Sep 181 Example Program DemoTranslateEnglishGUI.java.
TENTH LECTURE Event and listener. Events and Listeners An event can be defined as a type of signal to the program that something has happened. The event.
Mouse, Keyboard, Sounds, and Images JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin,
Prepared by: Dr. Abdallah Mohamed, AOU-KW Unit7: Event-driven programming 1.
10/20/2005week71 Graphics, mouse and mouse motion events, KeyEvent Agenda Classes in AWT for graphics Example java programs –Graphics –Mouse events –Mouse.
CSC 205 Programming II Lecture 5 AWT - I.
Events and Event Handling
Welcome To java
Programming in Java, 2e Sachin Malhotra Saurabh Choudhary.
CHAPTER Reacting to the user.
Programming in Java Sachin Malhotra, Chairperson, PGDM-IT, IMS Ghaziabad Saurabh Chaudhary, Dean, Academics, IMS Ghaziabad.
Handling User Events with Swing
Mouse Event Handling in Java (Review)
Event Handling Chapter 2 Objectives
Lecture 09 Applets.
Programming in Java Event Handling
GUI Programming using Java - Mouse Events
Making Java GUIs Functional
Presentation transcript:

Jan Event Handling -1.1 Yangjun Chen Dept. Business Computing University of Winnipeg

Jan Outline: 1.1 Events Comparing the Models Using the 1.1 Event Model: Step 1 -Listener interfaces -Adapters Using the 1.1 Event Model: Step 2 Using the 1.1 Event Model: Step 3 -The this keyword -make an applet to be its own listener Test Example EventTest Example Different Events

Jan Spots Applet import java. awt. Graphics; import java. awt. Color; import java. awt. Event; public class Spots extends java. applet. Applet { final int MAXSPOTS = 10; int xspots[] = new int[ MAXSPOTS]; int yspots[] = new int[ MAXSPOTS]; int currspots = 0; public void init() { setBackground( Color. white); } // end of init method

Jan Spots Applet public boolean mouseDown( Event e, int x, int y) { if (currspots < MAXSPOTS) { addspot( x, y); return true; } else { System. out. println(“ Too many spots!!”); return false; } } // end of the mouseDown method

Jan Spots Applet void addspot( int x, int y) { xspots[ currspots] = x; yspots[ currspots] = y; currspots++; repaint(); } // end of addspot method public void paint( Graphics g) { g. setColor( Color. blue); for (int i= 0; i< currspots; i++) { g. fillOval( xspots[ i] - 10, yspots[ i] - 10, 20, 20); } } // end of paint method } // end of class

Jan Java 1.1 Model The biggest difference between the two models is that event processing is separated into two parts in the 1.1 model. -First part is the object that receives the event: your applet, or part of the applet such as a button -Second part is the event listener mouse listener, key listener, scrolling listener, … responsible for doing something in response to these specific events The event receiver and listener are linked by listener registration. event receiver a component listener a class implement some listener interface registration a method call like: addActionListener(c)

Jan Java 1.1 Model Event (button pressed) Event (mouse click) Event (key pressed) applet Init( ) … register Mouse listener register Choice listener Registered Button listener Registered Mouse listener

Jan Java 1.1 Model You would register listeners to your program by calling up a special method which says that “this listener will process these events”. In this new model, your applet will only receive the events that have a listener registered. This will improve the efficiency of handling events for the system and your applet, since it doesn’t have to test every event that is generated. So, in the 1.02 model, all events are handled by your applet and in the 1.1 model, events are more distributed.

Jan Java 1.02 Model Event (button pressed) Event (mouse click) Event (key pressed) handleEvent( ) mouseUP() keyUP() applet Not handled

Jan Java 1.1 Model In the 1.02 model, all events were instances of the Event class. In the 1.1 model there are different classes for different events. These classes are all contained in the java. awt. Events package: -MouseEvent -MouseMotionEvent -KeyEvent -ActionEvent -ItemEvent -TextEvent -ComponentEvent, ContainerEvent, WindowEvent

Jan From the previous two figures, we see that in the 1.02 model, the applet looks at all the events that are generated. In the 1.1 model, the applet only looks at the ones that are registered and ignores the other ones. Java 1.1 Model

Jan Java 1.1 Model Features Any Component can be the source of an event just as in the 1.02 model Any class can be a listener for an event, by implementing the right listener interface. For example, a class that is to handle a Button’s event would have to implement the ActionListener interface. The events that are generated by a source Component are localized to only those listeners that have been registered. They will not be handed up the GUI (containment) hierarchy. This seems complicated but is actually quite simple.

Jan Java 1.1 Model Features Using Java 1.1 event model Which events? Implementing listener interfaces Registration

Jan Step 1: Which Events? The first step is to figure out what events you want to handle in your applet. You had to do this in the 1.02 model as well, but it is more explicit in the 1.1 model. In this model (1.1), different events correspond to different listeners, which means different methods. The different listeners are defined by different interfaces in the java.awt.events package.

Jan So you have to figure out which listener interface can handle the event that will be generated. -MouseListener -MouseMotionListener -KeyListener -ActionListener -ItemListener -TextListener …... What is an interface?

Jan Interfaces Java allows for single inheritance only. This makes relationships between classes and the functionality between them easier to understand. But there are times when you want to share certain behaviours between classes, but you can’t inherit more than one class. To get around this, Java uses the concept of interfaces, which gather method names together and then let you add those methods to classes that need them.

Jan Interfaces An interface is only a collection of method names without definitions. Sounds like an abstract class. Anywhere you can use a class, you can use an interface. Classes are extended but interfaces are implemented.

Jan Interfaces & Adapters When implementing an interface, all the methods that are in the interface must be provided with an implementation. Now, there are listeners in which you might not use all of the methods, so you wouldn’t want to implement them. In these cases, Java provides seven abstract adapter classes. Each of these classes will implement the appropriate listener interface, using methods with a no-statement body {}, rather than no implementation.

Jan Adapters So these adapter classes can be subclassed so that only the methods you want to use need to be implemented. The adapter classes are: - ActionAdapter - KeyAdapter - ContainerAdapter - FocusAdapter - MouseAdapter - MouseMotionAdapter - WindowAdapter

Jan Adapters For example, the following only implements the mousePressed()event handler: import java. awt. event.*; class Test extends MouseAdapter { public void mousePressed( MouseEvent e) { // statements }//end of mousePressed }//end of test import java. awt. event.*; class Test implements MouseListener { …... public void mousePressed( MouseEvent e) { // statements }//end of mousePressed }//end of test

Jan Listener Interfaces MouseListener -mouse down: public void mousePressed( MouseEvent e) -mouse up: public void mouseReleased( MouseEvent e) -mouse enter: public void mouseEntered( MouseEvent e) -mouse exit: public void mouseExited( MouseEvent e) -mouse clicks: public void mouseClicked( MouseEvent e) MouseMotionListener -mouse move: public void mouseMoved( MouseMotionEvent e) -mouse drag: public void mouseDragged( MouseMotionEvent e) KeyListener -key down: public void keyReleased( KeyEvent e) -key up: public void keyPressed( KeyEvent e) -key typed: public void keyTyped( KeyEvent e)

Jan Listener Interfaces ActionListener -action: public void actionPerformed( ActionEvent e) ItemListener -list select: public void itemStateChanged( ItemEvent e) TextListener -text changed: public void textValueChanged( TextEvent e) FocusListener AdjustmentListener ComponentListener ContainerListener WindowListener

Jan Step 2: Implementing Interfaces Now that you know what listeners you need, you have to create (code) the listener. So basically, an event listener is a class that implements one or more interfaces. To have a class implement an interface, you would declare the class as per usual and then use the keyword implements followed by the specific listener types.

Jan Implementing Interfaces You can either create new classes that handle the events for your main applet or you can modify your applet so that it is its own listener. The first method is a much preferred method when your program has a lot of events to be handled. The second method is used for more simple applets.

Jan Separate Listener Class There are two ways that you can create a separate listener class. -Implement the interfaces that are needed -extend or subclass from an event adapter (see previous example Adapter example) Let’s redo the Adapter example so that we don’t subclass the adapter but we directly implement the interface. Notice that we now have to provide implementations for every one of the methods that are defined in the interface.

Jan Implementing Interfaces import java. awt. event.*; class Test implements MouseListener { public void mousePressed( MouseEvent e) { // statements } public void mouseClicked( MouseEvent e) {} public void mouseEntered( MouseEvent e) {} public void mouseExited( MouseEvent e) {} public void mouseReleased( MouseEvent e) {} }

Jan Listener Applets Instead of creating a separate class listener, the applet can be its own listener. To create an applet that is a listener, you just implement the appropriate listener interfaces by doing the following: -1) import java. awt. event.* -2) add the implements keyword followed by the listener interfaces separated by commas -3) fill in the stubs for the interfaces (all the methods) -4) add the code to process the events

Jan Listener Applets A class definition would look like the following: public class Test extends java. applet. Applet implements MouseListener, KeyListener { … public void mousePressed( MouseEvent e) { // statements } public void mouseClicked( MouseEvent e) {...} public void mouseEntered( MouseEvent e) {...} public void mouseExited( MouseEvent e) {...} public void mouseReleased( MouseEvent e) {...} …... }//end of Test

Jan Step 3: Registration The final step is to let the system know that you want to receive these events. To do this, you “register” the listener with the object that will receive the method. There are special methods that are used to register the listeners, one for each listener type: -addMouseListener(Mousehandling c) -addMouseMotionListener() -addKeyListener()

Jan Registration -addActionListener() -addItemListener() -addTextListener() -addFocusListener() -addAdjustmentListener() -addComponentListener() -addContainerListener() -addWindowListener()

Jan Registration All methods take in a single argument: an object that implements the appropriate interface. So, if your listener is implemented as a separate class, then you can create an instance of that listener class and pass it to the right registration method. For example: Test ml = new Test(); // test implemented MouseListener addMouseListener(ml); If you modified your applet to be its own listener, use this as the argument to the listener registration method: -addMouseListener(this);

Jan Test Example import java. awt.*; public class Test extends java. applet. Applet { private Button left = new Button(“ Left”); private Button right = new Button(“ Right”); private Display myDisplay; public void init() { setLayout( new BorderLayout()); myDisplay = new Display(); add(“ Center”, myDisplay); Panel p =new Panel(); p. add( left); p. add( right); add(“ South”, p); }// end of init method

Jan Test Example public boolean action( Event e, Object arg) { if (e. target == left) myDisplay. shiftDot(- 12); else if (e. target == right) myDisplay. shiftDot( 12); else return false; return true; } // end of action method }// end of Test class

Jan Test Example class Display extends Canvas { private Point center; public Display() { center = new Point( 50,50); setBackground( Color. white); } // end of Display constructor public void shiftDot( int xAmount) { center. x += xAmount; repaint(); } // end of shiftDot method

Jan Test Example Note that a button click is handle in the applet by calling up methods in the Display class. public void paint( Graphics g) { g. setColor( Color. red); g. fillOval( center. x - 5, center. y - 5, 10,10); } // end of paint method } // end of Display class

Jan EventTest Example import java. awt.*; import java. awt. event.*; public class EventTest extends java. applet. Applet { private Button left = new Button(“ Left”); private Button right = new Button(“ Right”); private Display myDisplay; public void init() { setLayout( new BorderLayout()); myDisplay = new Display(); add(“ Center”, myDisplay); Panel p =new Panel(); p. add( left); p. add( right); add(“ South”, p);

Jan EventTest Example // Register myDisplay with each button left. addActionListener (myDisplay); right. addActionListener (myDisplay); } // end of init method } // end of EventTest class class Display extends Canvas implements ActionListener { private Point center; public Display() { center = new Point( 50,50); setBackground( Color. blue); } // end of Display constructor

Jan EventTest Example public void actionPerformed( ActionEvent e) { // this must be implemented String direction = e. getActionCommand(); if (direction. equals(“Left”)) center. x -= 12; else if (direction. equals(“ Right”)) center. x += 12; repaint(); }// end of actionPerformed method public void paint( Graphics g) { g. setColor( Color. red); g. fillOval( center. x - 5, center. y - 5, 10, 10); } // end of paint method }// end of Display class

Jan EventTest Example This version is just a little bit shorter but more significant. In this example, the events are generated by the buttons and are sent to the listener myDisplay. The events are then handled in that listener class. The example shows how to change the applet so that the listener registration can be made. All that is needed is to change 6 lines of code in the applet class. There was no need to change any code in the Display class. This is an example showing how the 1.1 model separates the model and the view - i. e. separating the GUI( view) from the code that handles (model) the events.

Jan Events in Model 1.1 Action Events Item Events Key Events Mouse Events Mouse Motion Component Events Container Events Focus Event Text Events Window Events Adjustment Event

Jan Action Events An ActionEvent is generated when the user clicks on a Button, selects a MenuItem, double-clicks an item in a List, or presses in a TextField. addActionListener() public void actionPerformed(ActionEvent e) { … } - Listener method String getActionCommand() -returns a String identifying the source of the event. For Buttons, this is generally the Button’s label, for List items and MenuItems, it is usually the text of the item selected, and for TextField it is usually the contents of the field.

Jan Item Events An ItemEvent is generated when the user selects a Checkbox, a CheckboxMenuItem, a Choice item, or single-clicks a List item. -Note that these are all two state objects - selected or not There are actually two events within the ItemEvent class, depending on whether the user selected or deselected an item. There are two class constants that represent these events: -SELECTED and DESELECTED -e.getID()= ItemEvent.SELECTED

Jan Item Events addItemListener() public void itemStateChanged(ItemListener e) { … } - Listener method Object getItem() -this method returns the item selected. Usually a String representing the item’s text or label.

Jan Key Events KeyEvents are generated when the user presses or releases a key on the keyboard. addKeyListener() There are three different KeyEvents, a key press, a key release and a key typed. When a key is pressed and released, all three of these events are generated. -They are handled by the KeyListener methods: keyPresse(), keyRelease(), keyType() char getKeyChar() -returns a character corresponding to the key that was pressed. If the key doesn’t correspond to a Unicode character, this method returns constant CHAR_UNDEFINED

Jan Key Events boolean isActionKey() -This method returns true if the key was an action key, and false otherwise. Action keys are keys like the arrows, function keys F1 to F12, Delete, backspace, shift, PageUp, etc. All of these keys are recognized by Java and are associated with a “virtual key code” represent as class constants in the KeyEvent class. int getKeyCode() -returns one of the class constants corresponding to the key.

Jan Mouse Events A MouseEvent is generated when the mouse is clicked or moved. addMouseListener() Listener methods: -mouseClicked() -mouseEntered() -mouseExited() -mousePressed() -mouseReleased()

Jan Mouse Events int getX( ) int getY( ) Point getPoint( ) -these methods return the x and y coordinates for the event or a Point representation of the coordinates. -They are all measured in the local coordinate system of the originating Component. int getClickCount( ) returns the click count for this event.