CSE 501N Fall ‘09 20: Event Handling and Inner Classes 17 November 2009 Nick Leidenfrost.

Slides:



Advertisements
Similar presentations
Event-Driven Programming Thus far, our programs have been executed one statement after the other However, many programs depend on user actions to dictate.
Advertisements

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.
Events ● Anything that happens in a GUI is an event. For example: – User clicks a button, presses return when typing text, or chooses a menu item ( ActionEvent.
1 Event Driven Programming with Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
Intermediate Java1 An example that uses inner classes Week Four Continued.
Lecture 18 Review the difference between abstract classes and interfaces The Cloneable interface Shallow and deep copies The ActionListener interface,
EVENTS CSC 171 FALL 2004 LECTURE 16. “Traditional” Input In console applications, user input is under control of the program The program asks the user.
Chapter 6: Graphical User Interface (GUI) and Object-Oriented Design (OOD) J ava P rogramming: Program Design Including Data Structures Program Design.
ACM/JETT Workshop - August 4-5, ExceptionHandling and User Interfaces (Event Delegation, Inner classes) using Swing.
1 Event Driven Programming wirh Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
Java Programming: From Problem Analysis to Program Design, Second Edition1  Learn about basic GUI components.  Explore how the GUI components JFrame,
1 CSC111H Graphical User Interfaces (GUIs) Introduction GUIs in Java Understanding Events A Simple Application The Containment Hierarchy Layout Managers.
1 Event Driven Programs Rick Mercer. 2 So what happens next?  You can layout a real pretty GUI  You can click on buttons, enter text into a text field,
More Event Handling Adapters Anonymous Listeners Pop menus Validating User Input.
Chapter 12 Event Handling. Chapter Goals To understand the Java event model To install action and mouse event listeners To accept input from buttons,
CS 11 java track: lecture 4 This week: arrays interfaces listener classes inner classes GUI callbacks.
Java GUI’s are event driven, meaning they generate events when the user interacts with the program. Typical events are moving the mouse, clicking a mouse.
Previous programs used a JLabel for OUTPUT. Another Swing component that can be used for both user input and output is the JTextfield. Suppose we want.
Fall 2006Adapded from Java Concepts Companion Slides1 Event Handling Advanced Programming ICOM 4015 Lecture 13 Reading: Java Concepts Chapter 12.
– Advanced Programming P ROGRAMMING IN Lecture 21 Introduction to Swing.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Chapter Nine and Ten Graphics.
COMP 321 Week 2. Outline Event-Driven Programming Events, Event Sources, Event Listeners Button and Timer Events Mouse Events, Adapters.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 10 - Interfaces.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
For (int i = 1; i
© 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.
CS-1020 Dr. Mark L. Hornick 1 Event-Driven Programming.
Java GUI. Graphical User Interface (GUI) a list a button a text field a label combo box checkbox.
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.
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 10: Event Handling 1 Event Handling.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 6 Graphical User Interface (GUI) and Object-Oriented Design (OOD)
Java Programming: From Problem Analysis to Program Design, Second Edition1 Lecture 5 Objectives  Learn about basic GUI components.  Explore how the GUI.
CHAPTER 10 EVENT HANDLING. CHAPTER GOALS To understand the Java event model To install mouse and action listeners To accept mouse and text input To display.
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 10: Event Handling 1 Chapter 10 Event Handling.
Graphical User Interfaces A Graphical User Interface (GUI) in Java is created with at least three kinds of objects: –components, events, and listeners.
Event-Driven Programming CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
1 Event Driven Programs Rick Mercer. 2 So what happens next?  You can layout a real pretty GUI  You can click on buttons, enter text into a text field,
1 Event Handling – Lecture 4 Prepared by: Ahmad Ramin Rahimee Assistant Professor ICTI.
1/18H212Mouse and Timer Events H212 Introduction to Software Systems Honors Lecture #16: Mouse and Timer Events October 26, 2015.
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.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Event Handling and GUI Components.
Swing GUI Components So far, we have written GUI applications which can ‘ draw ’. These applications are simple, yet typical of all Java GUI applications.
Lesson 28: More on the GUI button, frame and actions.
UQC117S2 Graphics Programming Lecture 2 Event Handling Program as a sequence of instructions Event -driven program Need to detect the event and carry out.
MIT AITI 2004 Swing Event Model Lecture 17. The Java Event Model In the last lecture, we learned how to construct a GUI to present information to the.
Prepared by: Dr. Abdallah Mohamed, AOU-KW Unit7: Event-driven programming 1.
1 Event Driven Programming with Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
CSC 205 Programming II Lecture 5 AWT - I.
Events and Event Handling
Chapter 14 Event-Driven Programming
CompSci 230 S Programming Techniques
GUI Programming III: Events
Event-driven programming for GUI
Chapter 12 Event Handling
Inner Classes 29-Nov-18.
Web Design & Development Lecture 12
Web Design & Development Lecture 13
Events, Event Handlers, and Threads
Constructors, GUI’s(Using Swing) and ActionListner
Inner Classes 17-Apr-19.
Inner Classes 21-Apr-19.
Making Java GUIs Functional
Inner Classes 1-May-19.
Inner Classes 11-May-19.
Inner Classes 18-May-19.
Presentation transcript:

CSE 501N Fall ‘09 20: Event Handling and Inner Classes 17 November 2009 Nick Leidenfrost

2 Lecture Outline Event Handling  Mostly in the context of GUIs  Mouse interaction  Keyboard interaction  Window interaction Inner Classes  Static inner classes  Member classes  Local classes  Anonymous inner classes

3 Events, Event Sources, and Event Listeners User interface events include key presses, mouse moves, button clicks, and so on Most programs don't want to be flooded by event notifications  Subscribe only to events we are interested in A program can indicate that it only cares about certain specific events

4 Events, Event Sources, and Event Listeners Event listener:  Notified when event happens  Belongs to a class that is provided by the application programmer  Its methods describe the actions to be taken when an event occurs  A program indicates which events it needs to receive by creating and registering event listener objects Event source:  … the thing that generates the event  When an event occurs, the event source notifies all event listeners

5 Events, Event Sources, and Event Listeners Example: Use JButton components for buttons; attach an ActionListener to each button ActionListener interface: Need to supply a class whose actionPerformed method contains instructions to be executed when button is clicked public interface ActionListener { void actionPerformed(ActionEvent event); }

6 Events, Event Sources, and Event Listeners event parameter contains details about the event, such as the time at which it occurred  Different types of events hold different information (mouse, key, action, scroll, etc.) Construct an object of the listener and add it to the button: // Code example ActionListener listener = new ClickListener(); button.addActionListener(listener);

7 File ClickListener.java import java.awt.event.ActionEvent; import java.awt.event.ActionListener; /** An action listener that prints a message. */ public class ClickListener implements ActionListener { public void actionPerformed(ActionEvent event){ System.out.println("I was clicked."); } }

8 File ButtonTester.java import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; /** This program demonstrates how to install an action listener. */ public class ButtonTester { public static void main(String[] args) { JFrame frame = new JFrame(); JButton button = new JButton("Click me!"); frame.add(button);

9 File ClickListener.java ActionListener listener = new ClickListener(); button.addActionListener(listener); frame.setSize(FRAME_WIDTH, FRAME_HEIGHT); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } private static final int FRAME_WIDTH = 100; private static final int FRAME_HEIGHT = 60; }

10 File ClickListener.java Output:

11 Mouse Events Use a MouseListener to capture mouse events Implement the MouseListener interface: public interface MouseListener { void mousePressed(MouseEvent event); // Called when a mouse button has been pressed on a component void mouseReleased(MouseEvent event); // Called when a mouse button has been released on a component void mouseClicked(MouseEvent event); // Called when the mouse has been clicked on a component void mouseEntered(MouseEvent event); // Called when the mouse enters a component void mouseExited(MouseEvent event); // Called when the mouse exits a component }

12 Mouse Events mousePressed, mouseReleased : called when a mouse button is pressed or released mouseClicked : if button is pressed and released in quick succession, and mouse hasn't moved mouseEntered, mouseExited : mouse has entered or exited the component's area

13 Mouse Events Add a mouse listener to a component by calling the addMouseListener method: We can add a MouseListener to any Component in our GUI // Code Example public class MyMouseListener implements MouseListener { // Implements five required methods } MouseListener listener = new MyMouseListener(); component.addMouseListener(listener);

14 Mouse Events class MousePressListener implements MouseListener { public void mousePressed(MouseEvent event) { int x = event.getX(); int y = event.getY(); component.moveTo(x, y); } // Do-nothing methods public void mouseReleased(MouseEvent event) {} public void mouseClicked(MouseEvent event) {} public void mouseEntered(MouseEvent event) {} public void mouseExited(MouseEvent event) {} } All methods of the interface must be implemented (Undesired methods may be left empty)

15 Window Listeners Generate events when some aspect of a graphical window changes  By default, window behaviors are not implemented Why is one interested in window events?  Useful to implement your shut down protocol Maybe save some stuff to disk, etc.  Stop your program from running

16 WindowListener interface windowActivated (WindowEvent e) windowActivated windowClosed (WindowEvent e) windowClosed windowClosing (WindowEvent e) windowClosing windowDeactivated (WindowEvent e) windowDeactivated windowDeiconified (WindowEvent e) windowDeiconified windowIconified (WindowEvent e) windowIconified windowOpened (WindowEvent e) windowOpened

17 Some shortcuts are available JFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Adapter classes  Saves you from writing empty method stubs for events you don’t want to monitor java.awt.event.MouseAdapter java.awt.event.KeyAdapter java.awt.event.WindowAdapter // Code Examples

18 Inner classes Sometimes we define a class whose purpose is only to "help out" another class.  E.g. Iterator or Node within LinkedList In some situations, it is nice if the helper class didn't stand on its own, but instead was more closely associated with the parent class itself.

19 Inner classes So far, all classes we have defined have been “top level” classes.  as far as the Java compiler is concerned, the classes are independent and exist on there own. We can do some things to group classes  Put classes in the same file  Packages These are useful but do not imply (or allow) a very close association  Use Inner Classes

20 Types of Inner Classes Nested top-level class Member class Local class Anonymous class Let us look at each one in more detail

21 Example public class Animation extends Component { public Animation(....){... addMouseListener( new AnimationRequestHandler() );... } public void beginAnimation() { // To be called when component is clicked... }

22 Nested Top Level Class This is a class defined as a static class member.  It’s still really a top-level class, but from outside its name is prefixed with the name of the containing class separated by a dot: Access to the class can be controlled through protection modifiers. LinkedList.Node node;

23 Example public class Animation extends Component{ public Animation(....){... addMouseListener( new AnimationRequestHandler() );.... } public void beginAnimation() {... } private static class AnimationRequestHandler extends MouseAdapter{ public void mouseClicked (MouseEvent e){ Animation anim = (Animation)e.getSource(); anim.beginAnimation(); }

24 Example beginAnimation() must be public because  AnimationRequestHandler is a top level class and has no special access to methods in Animation,  The inner class AnimationRequestHandler can access only public methods and public instance variables of the Animation class (like any other class), not private ones. Just like with any other method, you must use objectName.methodName() notation for beginAnimation().

25 Member Classes These are not top level classes  They are declared inside the class body like instance variables and methods (not static)  Each instance of a member class has a corresponding instance of the containing class (an implicit link to an instance of its parent class - usually the instance that created it)  Instances of member classes have access to the instance variables and methods of the containing class (and vice versa), as well as other member class instance variables and methods created by the original class.

26 Example public class Animation extends Component { public Animation(....){... addMouseListener( new AnimationRequestHandler() );... } void beginAnimation () {... } private class AnimationRequestHandler extends MouseAdapter { public void mouseClicked(MouseEvent e){ beginAnimation(); }

27 Example beginAnimation() does not need to be public because AnimationRequestHandler is member class and has access to methods in Animation  the member class AnimationRequestHandler can access any method or instance variable of the Animation class. This time beginAnimation() can be called without a source because there is only one object it could belong to. Technical Note: Member classes can't contain any static members and they can't have the same name as any containing class or package.

28 Local Classes These are similar to member classes  The have access to all class members Local classes are different than member classes in that  They are declared within a method or constructor  They also have access to final local variables within the scope in which they are declared  They are only visible and usable within the scope of their containing method / constructor Local classes have the same restrictions as member classes:  local classes can't contain any static members and they can't have the same name as any containing class or package.

29 Example public class Animation extends Component { public Animation(....){ class AnimationRequestHandler extends MouseAdapter{ public void mouseClicked(MouseEvent e){ beginAnimation(); }... addMouseListener( new AnimationRequestHandler() );... } void beginAnimation () {... }

30 Anonymous Inner Classes These are similar to local classes, except they have no names. Instead, they are defined within the expression that instantiates them. Anonymous classes must either extend a class, or implement an interface (and extend Object)  Why? We need some named way to access a defined API.

31 Example public class Animation extends Component { public Animation(....){... addMouseListener( new MouseAdapter(){ public void mouseClicked(MouseEvent e){ beginAnimation(); } });... } void beginAnimation () {... }

32 Notes on Anonymous Classes MouseAdapter is the name of the class being extended or interface being implemented. Any parameters to the constructer for MouseAdapter need to be included. An anonymous class inherits its constructor because it is never given the chance to define its own. An anonymous class has no name. An anonymous class has no protection modifiers - it has no name, so you can't access it from outside anyway.

33 Inner Classes as Listeners Example: investment viewer program; whenever button is clicked, interest is added, and new balance is displayed

34 Processing Text Input Use JTextField components to provide space for user input Place a JLabel next to each text field Supply a button that the user can press to indicate that the input is ready for processing int FIELD_WIDTH = 10; // In characters JTextField rateField = new JTextField(FIELD_WIDTH); JLabel rateLabel = new JLabel(“Interest Rate: ");

35 Processing Text Input The button's actionPerformed method reads the user input from the text fields (use getText ) class AddInterestListener implements ActionListener { public void actionPerformed (ActionEvent event) { double rate = Double.parseDouble(rateField.getText());... } }

36 Conclusion Questions? In Lab Now