470 likes | 488 Views
Event Handling -1.1 Yangjun Chen Dept. Business Computing University of Winnipeg. 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
E N D
Event Handling -1.1 Yangjun Chen Dept. Business Computing University of Winnipeg
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
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
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
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
a component a method call like: addActionListener(c) event receiver registration 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 . a class implement some listener interface listener
Java 1.1 Model applet Event (button pressed) Init( ) … register Mouse listener register Choice listener Event (mouse click) Registered Button listener Event (key pressed) Registered Mouse listener
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.
Java 1.02 Model applet Event (button pressed) handleEvent( ) mouseUP() Event (mouse click) keyUP() Event (key pressed) Not handled
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
Java 1.1 Model • 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 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.
Java 1.1 Model Features Which events? Using Java 1.1 event model Implementing listener interfaces Registration
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.
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?
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.
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.
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.
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
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
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)
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
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.
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.
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.
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) {} }
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
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
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()
Registration - addActionListener() - addItemListener() - addTextListener() - addFocusListener() - addAdjustmentListener() - addComponentListener() - addContainerListener() - addWindowListener()
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);
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
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
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
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
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);
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
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
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.
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
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 <enter> 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.
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
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.
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
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.
Mouse Events • A MouseEvent is generated when the mouse is clicked or • moved. • addMouseListener() • Listener methods: • - mouseClicked() • - mouseEntered() • - mouseExited() • - mousePressed() • - mouseReleased()
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.