1 / 27

Event-Driven Programming

Event-Driven Programming. Procedural programming is executed in procedural order. In event-driven programming , code is executed upon activation of events.

lilac
Download Presentation

Event-Driven Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Event-Driven Programming • Procedural programming is executed in procedural order. • In event-driven programming, code is executed upon activation of events. • The modern approach to handling events is based on the delegation event model, which defines standard and consistent mechanisms to generate and process events.

  2. The Delegation Event Model • The concept is quite simple: 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. • Listener must register with a source in order to receive an event notification. This provides an important benefit: notifications are sent only to listeners that want to receive them.

  3. The Delegation Event Model • The advantage of this design is that the application logic that processes events is separated from the user interface logic that generates those events. • A user interface element is able to "delegate" the processing of an event to a separate piece of code.

  4. Events • In the delegation model, an event is an object that describes a state change in a source. An event can be defined as a type of signal to the program that something has happened. • The event is an object generated by external user actions such as mouse movements, mouse button clicks, and keystrokes, or by the operating system, such as a timer. • The GUI component on which an event is generated is called the source event.

  5. Event Classes The root class of all event classes is java.util.EventObj. The subclasses of EventObj deal with special types of events, such as button actions, window events, component events, mouse events, and keystrokes.

  6. User Actions, Source Object, and Event Type Source Event TypeUser Action Object Generated Clicked a button JButtonActionEvent Changed text JTextComponentTextEvent Double-clicked on a list item JListActionEvent Selected or deselected an item JListItemEvent with a single click Selected or deselected an item JComboBoxItemEvent Mouse moved or dragged Component MouseEvent Mouse pressed, released, clicked, entered, or exited Component MouseEvent Window opened, closed iconified, deiconified, closed Window WindowEvent Click a check box JCheckBox ItemEvent, ActionEvent Click a radio button JRadioButtonItemEvent, . . . ActionEvent

  7. Event Registration, Listening, and Handling

  8. Handling Action Events A listener has two major requirements: • It must have been registered with one or more sources to receive notifications about specific types of events. • It must implement methods to receive and process these notifications.

  9. Handling Action Events • A listener object must implement the corresponding listener interface. • For example: A listener for a JButtonmust implement the ActionListener interface. TheactionListener interface contains the actionPerformed(ActionEvent e) method (handler). • An event object is passed to the handling method. You can get useful data values from the event object for processing the event. Use e.getSource() to obtain the source object in order to determine whether it is a button, a check box, a menu item, etc.

  10. Selected Event Handlers Event Class Listener Interface Listener Methods (Handlers) ActionEvent ActionListener actionPerformed(ActionEvent e) ItemEvent ItemListener itemStateChanged(ItemEvent e) WindowEvent WindowListener windowClosing(WindowEvent e) windowOpened(WindowEvent e) ContainerEvent ContainerListener componentAdded(ContainerEvent e) componentRemoved(ContainerEvent) MouseEvent MouseListener mousePressed(MouseEvent e) mouseReleased(MouseEvent e) MouseMotionListener mouseDraged(MouseEvent e) mouseMoved(MouseEvent e) KeyEvent KeyListener keyPressed(KeyEvent e) keyReleased(KeyEvent e) keyTyped(KeyEvent e) TexEvent TextListener TextValueCnanged(TextEvent e)

  11. Example: Handling Simple Action Events Objective: Display two buttons in the window. A message is displayed on the console to indicate which button is clicked, when a button is clicked. 1. Create source of events (two buttons); 2. Add the buttons to the frame; 3. Register listeners to the buttons; 4. Implement (override) handler for the listener.

  12. 1. Handling Action Events: Source creation import javx.swing.*; import awt.*; import java.awt.event.*; public class TestActionEvent extends Jframe implements ActionListener { // 1st step: Createsources of events(two buttons) private JButton jbtOK = new Jbutton(“OK”); private JButton jbtCL = new Jbutton(“Cancel”);

  13. 2. Handling Action Events: Registration // Constructor public TestActionEvent () { setTitle(); Container cp = getContentPane(); cp.setLayout(new FlowLayout()); // 2nd step: Add the sources(buttons) to the frame cp.add(jbtOK); cp.add(jbtCL); // 3rd step: Register listeners to the sources; jbtOK.addActionListener(this); jbtCL.addActionListener(this); }

  14. 3. Handling Action Events // 4th step:implement handler public void actionPerformed(ActionEvent e) { if(e.getSource() == jbtOK) { System.out.println(“The OK button is clicked”); } if(e.getSource() == jbtCL) { System.out.println(“The Cancel button is clicked“); }// actionPerformed }

  15. 4. Handling Action Events: Test public static void main(String[] args) { TestActionEvent frame = new TestActionEvent(); frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); frame.setSize(100,100); frame.setVisible(true); }//main }// class

  16. Handling Action Events: Another Example public class Button2Demo extends JFrame { private JButton jbtOK, jbtCL; ActionListener handler = new ButtonHandler(); public Button2Demo() { jbtOK = new JButton(“OK”); jbtOK.addActionListener(handler); jbtCL = new JButton(“Cancel”); jbtCL.addActionListener(handler); } ...

  17. 2. Handling Action Events ... // Inner class class ButtonHandler implements ActionListener { public void actionPerformed(ActionEvent e) { if(e.getSource() == jbtOK) { System.out.println(“The OK button is pressed”); }//if if(e.getSource() == jbtCL) { System.out.println(“The Cancel button is pressed”); } //if }// actionPerformed() }// Inner class }// public class

  18. Example: Palindrome Demo

  19. 1. Declare UI Components import Palindrome; // Import class Palindrome class PalindromeDemo extends JFrame { // Three Buttons private JButton jbtClear, jbtCheck, jbtExit; // One Text Field for input private JTextField jtfString; // Labels for result and instruction private JLabel jlResult, jlInstr; // One action listener for the buttons ActionListener handler = new ButtonHandler();

  20. 2. Create UI Components public PalindromeDemo() { // Three Buttons jbtCheck = new JButton(“Check”); jbtClear = new JButton(“Clear”); jbtExit = new JButton(“Exit”); // One Text Field for input jtfString = new JTextField(32); // Labels for instruction and result jlInstr = new JLabel(“Enter phrase to be tested:”); jlResult = new JLabel(“”); ...

  21. 3. Add UI and Register Listener

  22. 4a. Implement Handler as Inner Class classButtonHandler implements ActionListener { public void actionPerformed(ActionEvent e) { if(e.getSource() == jbtClear) { jtfString.setText(“”); jlResult.setText(“”); }//if if(e.getSource() == jbtCheck) { String str = jtfString.getText(); Palindrome pal = new Palindreme(str); boolean result = pal.IsPalindrome(); if(result) jlResult.setText(“Yes”); else jlResult.setText(“No”); } //if if(e.getSource() == jbtExit) { System.exit(0); } }// actionPerformed() }// inner class ButtonHandler Use method of the class Palindrome to check the phrase.

  23. 4b. Implement Handler as Inner Class

  24. 5. Main method in the application public static void main(String[] args) { String title = “Is it Palindrome?”; // Create the frame with UI as an object of // PalindromeDemo Class. PalindromeDemo frame = new PalindromeDemo(title); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setsize(400,150); frame.setVisible(true); }//main

  25. Handler events with Anonymous Class // Another way to implement handlers private JButton jbtCheck = new JButton(”Check"); jbtCheck.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String str = jtfString.getText(); boolean result = isPalindrome(str) if(result == TRUE) jlResult.setText(”Yes"); else jlResult.setText(”No"); } });

  26. 2. Another way to handle events private JButton jbtClear = new JButton(”Clear"); jbtClear.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { jtfString.setText(""); jlResult.setText(""); } });

  27. 3. Another way to handle events private JButton jbtExit = new JButton(”Exit"); jbtExit.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { System.exit(0); } });

More Related