Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Event Handling - Web Design and Development - Lecture Handouts, Lecture notes of Web Design and Development

Event Handling, GUIs generate events, Event Handling Model, Event Handling Steps, Event Handling Process, Registering Handler with Generator, Event Handling Example. Virtual University is one of best in Pakistan for distance education in science.

Typology: Lecture notes

2011/2012

Uploaded on 11/10/2012

taariq
taariq 🇵🇰

4.4

(16)

59 documents

1 / 32

Toggle sidebar

Related documents


Partial preview of the text

Download Event Handling - Web Design and Development - Lecture Handouts and more Lecture notes Web Design and Development in PDF only on Docsity! Handout 11–1 Web Design & Development CS-506 - 136 - Event Handling One of the most important aspects of most non-trivial applications (especially UI type- apps) is the ability to respond to events that are generated by the various components of the application, both in response to user interactions and other system components such as client-server processing. In this handout we will look at how Java supports event generation and handling and how to create (and process) custom events. GUIs generate events when the user interacts with GUI. For example, — Clicking a button — Moving the mouse — Closing Window etc Both AWT and swing components (not all) generate events — java.awt.event.*; — javax.swing.event.*; In java, events are represented by Objects These objects tells us about event and its source. Examples are: — ActionEvent (Clicking a button) — WindowEvent (Doing something with window e.g. closing , minimizing) Some event classes of java.awt.event are shown in diagram below Class nam e Ke y java.lang.Object java.awt.AWTEvent ActionEvent ItemEvent AdjustmentEvent ComponentEvent java.util.EventObject ContainerEvent PaintEvent FocusEvent WindowEvent InputEvent KeyEvent MouseEventInterfa ce nam e Handout 11–1 Web Design & Development CS-506 - 137 - Event Handling Model In Java both AWT and Swing components use Event Delegation Model. – In this model processing of an event is delegated to a particular object (handlers ) in the program – It’s a Publish-Subscribe model. That is, event generating component publish an event and event handling components subscribe for that event. The publisher sends these events to subscribers. Similar to the way that you subscribe for newspaper and you get the newspaper at your home from the publisher. – This model separates UI code from program logic, it means that we can create separate classes for UI components and event handlers and hence business/program logic is separated from GUI components. Event Handling Steps For a programmer the event Handling is a three step process in terms of code – Step 1: Create components which can generate events (Event Generators) – Step 2: Build component (objects) that can handle events (Event Handlers) – Step 3: Register handlers with generators Event Handling Process Step 1: Event Generators The first step is that you create an event generator. You have already seen a lot of event generators like: – Buttons – Mouse – Key – Window etc Most of GUI components can be created by calling their constructors. For example JButton b1 = new JButton(“Hello”); Now b1 can generate events Note: We do not create Mouse/Keys etc as they are system components Handout 11–1 Web Design & Development CS-506 - 140 - Step 3: Registering Handler with Generator The event generator is told about the object which can handle its events Event Generators have a method — addXXXListener(_reference to the object of Handler class_) For example, if b1 is JButton then — b1.addActionListener(this); // if listener and generator are same class Handout 11–1 Web Design & Development CS-506 - 141 - Event Handling Example Clicking the “Hello” button will open up a message dialog shown below. We will take the simplest approach of creating handler and generator in a single class. Button is our event generator and to handle that event our class needs to implement ActionListener Interface and to override its actionPerformed method and in last to do the registration 1. import java.awt.*; 2. import javax.swing.*; 3. import java.awt.event.*; /* Implementing the interface according to the type of the event, i.e. creating event handler (first part of step 2 of our process) */ 4. public class ActionEventTest implements ActionListner{ 5. JFrame frame; 6. JButton hello; // setting layout components 7. public void initGUI ( ) { 8. frame = new JFrame(); 9. Container cont = frame.getContentPane(); 10. cont.setLayout(new FlowLayout()); //Creating event generator step-1 of our process 11. hello = new JButton("Hello"); /* Registering event handler with event generator. Since event handler is in same object that contains button, we have used this to pass the reference.(step 3 of the process) */ 12. hello.addActionListener(this); 13. cont.add(hello); Handout 11–1 Web Design & Development CS-506 - 142 - 14. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 15. frame.setSize(150, 150); 16. frame.setVisible(true); 17. } //constructor 18. public ActionEventTest ( ) { 19. initGUI(); 20. } /* Override actionPerformed method of ActionListener’s interfacemethod of which will be called when event takes place (second part of step 2 of our process) */ 21. public void actionPerformed(ActionEvent event) { 22. JOptionPane.showMessageDialog(null,"Hello is pressed"); 23. } 24. public static void main(String args[]) { 25. ActionEventTest aeTest = new ActionEventTest(); 26. } 27.} // end class Handout 11–2 Web Design & Development CS-506 - 145 - Making Small Calculator User enters numbers in the provided fields On pressing “+” button, sum would be displayed in the answer field On pressing “*” button, product would be displayed in the answer field Handout 11–2 Web Design & Development CS-506 - 146 - Example Code: Making Small Calculator 1. import java.awt.*; 2. import javax.swing.*; 3. import java.awt.event.*; 4. public class SmallCalcApp implements ActionListener{ 5. JFrame frame; 6. JLabel firstOperand, secondOperand, answer; 7. JTextField op1, op2, ans; 8. JButton plus, mul; 9. // setting layout 10. public void initGUI ( ) { 11. frame = new JFrame(); 12. firstOperand = new JLabel("First Operand"); 13. secondOperand = new JLabel("Second Operand"); 14. answer = new JLabel("Answer"); 15. op1 = new JTextField (15); 16. op2 = new JTextField (15); 17. ans = new JTextField (15); 18. plus = new JButton("+"); 19. plus.setPreferredSize(new Dimension(70,25)); 20. mul = new JButton("*"); 21. mul.setPreferredSize(new Dimension(70,25)); 22. Container cont = frame.getContentPane(); 23. cont.setLayout(new FlowLayout()); 24. cont.add(firstOperand); 25. cont.add(op1); 26. cont.add(secondOperand); 27. cont.add(op2); 28. cont.add(plus); 29. cont.add(mul); 30. cont.add(answer); 31. cont.add(ans); 32. plus.addActionListener(this); 33. mul.addActionListener(this); 34. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 35. frame.setSize(200, 220); 36. frame.setVisible(true); 37. } Handout 11–2 Web Design & Development CS-506 - 147 - 38. //constructor 39. public SmallCalcApp ( ) { 40. initGUI(); 41. } 42. public void actionPerformed(ActionEvent event) { 43. String oper, result; 44. int num1, num2, res; /* All the information regarding an event is contained inside the event object. Here we are calling the getSource() method on the event object to figure out the button that has generated that event. */ 45. if (event.getSource() == plus) { 46. oper = op1.getText(); 47. num1 = Integer.parseInt(oper); 48. oper = op2.getText(); 49. num2 = Integer.parseInt (oper); 50. res = num1+num2; 51. result = res+""; 52. ans.setText(result); 53. } 54. else if (event.getSource() == mul) { 55. oper = op1.getText(); 56. num1 = Integer.parseInt(oper); 57. oper = op2.getText(); 58. num2 = Integer.parseInt (oper); 59. res = num1*num2; 60. result = res+""; 61. ans.setText(result); 62. } 63. public static void main(String args[]) { 64. SmallCalcApp scApp = new SmallCalcApp(); 65. } 66. }// end class Handout 12–1 Web Design & Development CS-506 - 150 - Example Code: Handling Mouse Events Example to show Mouse Event Handling .Every time mouse is moved, the coordinates for a new place is shown in a label. 1. import java.awt.*; 2. import javax.swing.*; 3. import java.awt.event.*; 4. public class EventsEx implements MouseMotionListener{ 5. JFrame frame; 6. JLabel coordinates; 7. // setting layout 8. public void initGUI ( ) { 9. // creating event generator 10. frame = new JFrame(); 11. Container cont = frame.getContentPane(); 12. cont.setLayout(new BorderLayout( ) ); 13. coordinates = new JLabel (); 14. cont.add(coordinates, BorderLayout.NORTH); 15. // registring mouse event handler with generator 16. frame.addMouseMotionListener(this); 17. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 18. frame.setSize(350, 350); 19. frame.setVisible(true); 20. } // end initGUI method 21. //default constructor 22. public EventsEx ( ) { 23. initGUI(); 24. } // MouseMotionListener event hadler handling dragging 25. public void mouseDragged (MouseEvent me) { 26. int x = me.getX(); 27. int y = me.getY(); 28. coordinates.setText("Dragged at [" + x + "," + y + "]"); 29. } Handout 12–1 Web Design & Development CS-506 - 151 - // MouseMotionListener event handler handling motion 30. public void mouseMoved (MouseEvent me) { 31. int x = me.getX(); 32. int y = me.getY(); 33. coordinates.setText("Moved at [" + x + "," + y + "]"); 34. } 35. public static void main(String args[]) { 36. EventsEx ex = new EventsEx(); 37. } 38. } // end class Handout 12–1 Web Design & Development CS-506 - 152 - Another Example: Handling Window Events Task We want to handle Window Exit event only Why ? When window is closed, control should return back to command prompt. But we have already achieved this functionality through following line of code frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); But, what if we want to display some message (Good Bye) before exiting? How ? To handle window events, we need to implement “WindowListner” interface. “WindowListner” interface contains 7 methods We require only one i.e. windowClosing But, We have to provide definitions of all methods to make our class a concrete class WindowListener interface is defined in the JDK as follows public interface WindowListener { public void windowActivated(WindowEvent we); public void windowClosed(WindowEvent we); public void windowClosing(WindowEvent we); public void windowDeactivated(WindowEvent we); public void windowDeiconified(WindowEvent we); public void windowIconified(WindowEvent we); public void windowOpened(WindowEvent we); } public void windowClosing(WindowEvent we) is our required method When user closes the window, Message would be displayed After pressing Ok button program will exit Handout 13–1 Web Design & Development CS-506 - 155 - Problem in Last Code Example Problem – We were interested in windowClosing() method only – But have to provide definitions of all the methods, Why? – Because a class implementing an interface has to provide definitions of all methods present in that interface. Solution – To avoid giving implementations of all methods of an interface when we are not using these methods we use Event Adapter classes Adapter Classes • For listener interfaces containing more than one event handling methods, jdk defines adapter classes. Examples are – For WindowListener WindowAdapter – For MouseMotionListener MouseMotionAdapter – and many more • Adapter classes provide definitions for all the methods (empty bodies) of their corresponding Listener interface • It means that WindowAdapter class implements WindowListener interface and provide the definition of all methods inside that Listener interface • Consider the following example of MouseMotionAdapter and its corresponding MouseMotionListener interface public interface MouseMotionListener { public void mouseDragged (MouseEvent me); public void mouseMoved (MouseEvent me); } public class MouseMotionAdapter implements MouseMotionListener{ public void mouseDragged (MouseEvent me) { } public void mouseMoved (MouseEvent me) { } } Handout 13–1 Web Design & Development CS-506 - 156 - Available Adapter classes How to use Adapter Classes Previously handler class need to implement interface public class EventsEx implements MouseMotionListener{...} Therefore it has to provide definitions of all the methods inside that interface Now our handler class will inherit from adapter class public class EventsEx extends MouseMotionAdapter{...} Due to inheritance, all the methods of the adapter class will be available inside our handler class Since adapter classes has already provided definitions with empty bodies. We do not have to provide implementations of all the methods again We only need to override our method of interest. Adapter Class Listener (If Any) Registration Method ActionListener addActionListener AdjustmentListener addAdjustmentListener ComponentListener ComponentAdapter addComponentListener ContainerListener ContainerAdapter addContainerListener FocusListener FocusAdapter addFocusListener ItemListener addItemListener KeyListener KeyAdapter addKeyListener MouseListener MouseAdapter addMouseListener MouseMotionListener MouseMotionAdapter addMouseMotionListener TextListener addTextListener WindowListener WindowAdapter addWindowListener Handout 13–1 Web Design & Development CS-506 - 157 - Example Code 13.1: Handling Window Events using Adapter Classes Here we are modifying the window event code in the last example to show the use of WindowAdapter instead of WindowListener. Code related to MouseMotionListener is deleted to avoid cluttering of code. 1. import java.awt.*; 2. import javax.swing.*; 3. import java.awt.event.*; 4. public class EventsEx extends WindowAdapter { 5. JFrame frame; 6. JLabel coordinates; // setting layout 7. public void initGUI ( ) { // creating event generator 8. frame = new JFrame(); 9. Container cont = frame.getContentPane(); 10. cont.setLayout(new BorderLayout( ) ); 11. coordinates = new JLabel (); 12. cont.add(coordinates, BorderLayout.NORTH); // registering window handler with generator 13. frame.addWindowListener(this); 14. frame.setSize(350, 350); 15. frame.setVisible(true); 16. } // end initGUI method //default constructor 17. public EventsEx ( ) { 18. initGUI(); 19. } // As you can see that we have only implemented // our required method 20. public void windowClosing (WindowEvent we) { 21. JOptionPane.showMessageDialog(null, “Good Bye”); 22. System.exit(0); 23. } 24. public static void main(String args[]) { 25. EventsEx ex = new EventsEx(); 26. } 27. } // end class Handout 13–1 Web Design & Development CS-506 - 160 - Example Code 13.3: Handling Window and Mouse Events with Inner Class Here we are modifying the window event code of the last example to handle window and mouse events using inner classes. The diagram given below summarizes the approach. 1. import java.awt.*; 2. import javax.swing.*; 3. import java.awt.event.*; 4. public class EventEx { 5. JFrame frame; 6. JLabel coordinates; 7. // setting layout 8. public void initGUI ( ) { 9. frame = new JFrame(); 10. Container cont = frame.getContentPane(); 11. cont.setLayout(new BorderLayout( ) ); 12. coordinates = new JLabel (); 13. cont.add(coordinates, BorderLayout.NORTH); /* Creating an object of the class which is handling our window events and registering it with generator */ 14. WindowHandler whandler = new WindowHandler (); 15. frame.addWindowListener(whandler); /* Creating an object of the class which is handling our MouseMotion events & registering it with generator */ 16. MouseHandler mhandler = new MouseHandler (); 17. frame.addMouseMotionListener(mhandler); 18. frame.setSize(350, 350); 19. frame.setVisible(true); 20. } Outer class for GUI and other code Inner class Handling Mouse Events Inner class Handling Window Handout 13–1 Web Design & Development CS-506 - 161 - //default constructor 21. public EventEx ( ) { 22. initGUI(); 23. } /* Inner class implementation of WindowAdapter. Outer class is free to inherit from any other class. */ 24. private class WindowHandler extends WindowAdapter { // Event Handler for WindowListener 25. public void windowClosing (WindowEvent we) { 26. JOptionPane.showMessageDialog(null, “Good Bye”); 27. System.exit(0) 28. } 29. } // end of WindowHandler //Inner class implementation of MouseMotionAdapter 30. private class MouseHandler extends MouseMotionAdapter { // Event Handler for mouse motion events 31. public void mouseMoved (MouseEvent me) { 32. int x = me.getX(); 33. int y = me.getY(); 34. coord.setText(“Moved at [" + x + "," + y + "]” ); 35. } 36. } // end of MouseHandler 37. public static void main(String args[]) { 38. EventEx e = new EventEx(); 39. } 40. } // end class Handout 13–1 Web Design & Development CS-506 - 162 - Example Code: Making Small Calculator using Inner classes User enters numbers in the provided fields On pressing “+” button, sum would be displayed in the answer field On pressing “*” button, product would be displayed in the answer field Handout 13–1 Web Design & Development CS-506 - 165 - Anonymous Inner Classes Has no name Same as inner class in capabilities much shorter difficult to understand Named vs. Anonymous Objects Named – String s = “hello”; System.out.println(s); – “hello” has a named reference s. Anonymous – System.out.println(“hello”); We generally use anonymous object when there is just a one time use of a particular object but in case of a repeated use we generally used named objects and use that named reference to use that objects again and again. Handout 13–1 Web Design & Development CS-506 - 166 - Example Code 13.4 Handling Window Event with Anonymous Inner Class Here we are modifying the window event code of 13.3 to show the use of anonymous inner class. 28. import java.awt.*; 29. import javax.swing.*; 30. import java.awt.event.*; 31. public class EventsEx extends WindowAdapter { 32. JFrame frame; 33. JLabel coordinates; // setting layout 34. public void initGUI ( ) { // creating event generator 35. frame = new JFrame(); 36. Container cont = frame.getContentPane(); 37. cont.setLayout(new BorderLayout( ) ); 38. coordinates = new JLabel (); 39. cont.add(coordinates, BorderLayout.NORTH); // registering event handler (anonymous inner class) // with generator by using 40. frame.addWindowListener ( 41. new WindowAdapter ( ) { 42. public void windowClosing (WindowEvent we) { 43. JOptionPane.showMessageDialog(null, “Good Bye”); 44. System.exit(0); 45. } // end window closing 46. } // end WindowAdapter 47. ); // end of addWindowListener 48. frame.setSize(350, 350); 49. frame.setVisible(true); 50. } // end initGUI method //default constructor 51. public EventsEx ( ) { 52. initGUI(); 53. } 54. public static void main(String args[]) { 55. EventsEx ex = new EventsEx(); 56. } 57. } // end class Handout 13–1 Web Design & Development CS-506 - 167 - Summary of Approaches for Handling Events 1. By implementing Interfaces 2. By extending from Adapter classes To implement the above two techniques we can use Same class • putting event handler & generator in one class Separate class 1. Outer class • Putting event handlers & generator in two different classes 3. Inner classes 3. Anonymous Inner classes
Docsity logo



Copyright © 2024 Ladybird Srl - Via Leonardo da Vinci 16, 10126, Torino, Italy - VAT 10816460017 - All rights reserved