Programming Languages 2nd edition Tucker and Noonan Chapter 16 Event-Driven Programming Of all men s miseries the bitterest is this, to know so much and to have control over nothing. Herodotus (484-432 BC) Contents 16.1 Event-Driven Control 16.2 Event Handling 16.3 Three Examples 16.4 Other Applications 16-2 1
16.1 Event-Driven Control A conventional model of computation has the program prescribe the exact order of input. Programs terminate once the input is exhausted. Event-driven programs do not control the sequence in which input events occur. An event is created by an external action such as a user interaction through a GUI The event handler is a segment of code that is called in response to an event 16-3 Examples GUI applications: Model-View-Controller design Embedded applications: cell phones car engines airplanes 16-4 2
Imperative and Event-Driven Paradigms Contrasted Figure 16.1 16-5 Input to an event-driven program comes from autonomous event sources. Eg: human, robot sensors, engine sensors. 16-6 3
Properties 1. An event-driven program has no perceived stopping point. 2. The traditional read-eval-print loop does not explicitly appear. A typical program processes an input and exits. 16-7 Model-View-Controller (MVC) Model: the object being implemented. Ex: game, calculator. Controller: input mechanisms. Ex: buttons, menus, combo boxes. View: output. 16-8 4
Model-View-Controller (MVC) Ex: Tic-Tac-Toe Model Whose turn is it? State of the board. Has someone won? Are there no empty squares? 16-10 5
Events in Java Subclasses of AWTEvent Event sources in Swing are subclasses of JComponent Program must listen for events Ex: for a JButton b b.addactionlistener(listener) 16-11 Events in Java (continued) An event generator tells a listener of an event by sending a message An interface is used to make event-handling methods conform to a standard protocol A class that implements a listener must implement an interface for the listener Concepts of Programming Languages, Copyright 2006 9th ed., The by McGraw-Hill Robert W. Companies, Sebesta. Addison Inc. Wesley, 2010. 16-12 6
Events in Java (continued) One class of events is ItemEvent, which is associated with the event of clicking a checkbox, a radio button, or a list item The ItemListener interface prescribes a method, itemstatechanged, which is a handler for ItemEvent events The listener is created with additemlistener Concepts of Programming Languages, Copyright 2006 9th ed., The by McGraw-Hill Robert W. Companies, Sebesta. Addison Inc. Wesley, 2010. 16-13 Java Class AWTEvent and Its Subclasses* Figure 16.2 16-14 7
16-15 Java EventListener Class Interface and Its Subclasses* Figure 16.4 16-16 8
Widget Listener Interface JButton ActionListener actionperformed JComboBox ActionListener actionperformed JLabel JTextArea ActionListener actionperformed JTextField ActionListener actionperformed MouseListener... MouseMotionListener... 16-17 Java GUI Application A GUI application is a program that runs in its own window and communicates with users using buttons, menus, mouse clicks, etc. A GUI application often has a paint method, which is invoked whenever the application needs to repaint itself. 16-18 9
import javax.swing.jframe; public class GUIApp { public static void main (String[ ] args) { JFrame frame = new JFrame(); frame.setdefaultcloseoperation( JFrame.EXIT_ON_CLOSE); MyApp app = new MyApp( ); // JPanel frame.getcontentpane().add(app); frame.show( ); } } 16-19 16.3.1 A Simple GUI Interface combo : Nothing, Rectangle, Message echoarea : report events typing : enter messages 16-20 10
Initial Frame Design for a Graphical Drawing Tool Figure 16.6 16-21 private int lastx = 0; private int lasty = 0; private int clicknumber = 0; private JComboBox combo; private String[ ] choices = {"Nothing", "Rectangle", "Message"}; private JTextArea echoarea; private JTextField typing; 16-22 11
public Skeleton( ) { // Set the background color and mouse listener setbackground(color.white); addmouselistener(new MouseHandler()); // Add a button to the Panel. JButton clearbutton = new JButton("Clear"); clearbutton.setforeground(color.black); clearbutton.setbackground(color.lightgray); add(clearbutton); clearbutton.addactionlistener( new ClearButtonHandler()); 16-23 // Create a menu of user combos and add it combo = new JComboBox(choices); add(combo); combo.addactionlistener( new ComboHandler()); // Add a TextField and a TextArea typing = new JTextField(20); add(typing); typing.addactionlistener(new TextHandler()); echoarea = new JTextArea(2, 40); echoarea.seteditable(false); add(echoarea); } 16-24 12
private class ComboHandler implements ActionListener { public void actionperformed (ActionEvent e) { String c = (String) (combo.getselecteditem()); echoarea.settext("combo selected: " + c); clicknumber = 0; if (c.equals("rectangle")) echoarea.append("\nclick to set upper " + " left corner of the rectangle"); else if (c.equals("message")) echoarea.append( "\nenter a message in the text area"); }} 16-25 First Step in an Interaction: The User Selects Rectangle from the Menu Figure 16.9 16-26 13
private class MouseHandler extends MouseAdapter { public void mouseclicked(mouseevent e) { int x = e.getx(); int y = e.gety(); echoarea.settext("mouse Clicked at " + e.getx() + ", " + e.gety() + "\n"); Graphics g = getgraphics(); if (combo.getselecteditem(). equals("rectangle")) { clicknumber = clicknumber + 1; 16-27 // is it the first click? if (clicknumber % 2 == 1) { echoarea.append("click to set lower right" + " corner of the rectangle"); lastx = x; lasty = y; } // or the second? else g.drawrect(lastx, lasty, Math.abs(x-lastX), Math.abs(y-lastY)); } 16-28 14
else if (combo.getselecteditem().equals("message")) // for a message, display it g.drawstring(typing.gettext(), x, y); } // mouseclicked } 16-29 Effect of Selecting Rectangle Choice and Clicking the Mouse Twice Figure 16.12 16-30 15
public static void main(string args[]) { JFrame frame = new JFrame(); frame.setdefaultcloseoperation( JFrame.EXIT_ON_CLOSE); Skeleton panel = new Skeleton( ); } frame.getcontentpane().add(panel); frame.setsize(500, 500); frame.show(); 16-31 16