More Event Handling Adapters Anonymous Listeners Pop menus Validating User Input.

Slides:



Advertisements
Similar presentations
Event handling and listeners What is an event? user actions and context event sources and listeners Why should my programs be event- driven? User interaction.
Advertisements

Introduction to Java 2 Programming
Graphic User Interfaces Layout Managers Event Handling.
Event-Driven Programming Thus far, our programs have been executed one statement after the other However, many programs depend on user actions to dictate.
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.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 14 Event-Driven Programming.
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.
For IST410 Students only Events-1 Event Handling.
Event-Driven Programming
Unit 12 Object-oriented programming: Event-driven programming for GUI Jin Sa.
OOP Java1 Event Handling Overview Listeners, Adapters and Event Sources Inner classes Event Handling Details Applets and GUI Applications Event.
Object-Oriented Software Engineering PersonGui (Mark 2) Case Study.
Intermediate Java1 An example that uses inner classes Week Four Continued.
1 lecture 12Lecture 13 Event Handling (cont.) Overview  Handling Window Events.  Event Adapters Revisited.  Introduction to Components and Containers.
Lecture 18 Review the difference between abstract classes and interfaces The Cloneable interface Shallow and deep copies The ActionListener interface,
GUI Event Handling Nithya Raman. What is an Event? GUI components communicate with the rest of the applications through events. The source of an event.
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,
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.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 14 Event-Driven Programming.
(c) University of Washington07b-1 CSC 143 Java Events, Event Handlers, and Threads Reading: Ch. 17.
CSE 501N Fall ‘09 20: Event Handling and Inner Classes 17 November 2009 Nick Leidenfrost.
COMP 321 Week 2. Outline Event-Driven Programming Events, Event Sources, Event Listeners Button and Timer Events Mouse Events, Adapters.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 12 Event-Driven Programming.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Creating a GUI with JFC/Swing. What are the JFC and Swing? JFC –Java Foundation Classes –a group of features to help people build graphical user interfaces.
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.
Anonymous Classes An anonymous class is a local class that does not have a name. An anonymous class allows an object to be created using an expression.
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.
Lesson 6 Programming Techniques Event Handling /EvH/ AUBG ICoSCIS Team Assoc. Prof. Stoyan Bonev March, , 2013 SWU, Blagoevgrad.
Object Oriented Programming.  Interface  Event Handling.
Agenda Introduction. Event Model. Creating GUI Application. Event Examples.
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 10: Event Handling 1 Event Handling.
GUI DYNAMICS Lecture 11 CS2110 – Fall GUI Statics and GUI Dynamics  Statics: what’s drawn on the screen  Components buttons, labels, lists, sliders,
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 10: Event Handling 1 Chapter 10 Event Handling.
Event-Driven Programming CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Creating a GUI Class An example of class design using inheritance and interfaces.
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,
Event-Driven Programming F Procedural programming is executed in procedural order. F In event-driven programming, code is executed upon activation of events.
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.
1 Chapter 3 Event-Driven Programming. 2 Objectives F To explain the concept of event-driven programming (§12.2). F To understand event, event source,
CSI 3125, Preliminaries, page 1 Event Handling. CSI 3125, Preliminaries, page 2 Event Handling An Event Change in the state of an object is known as event.
Mouse Events GUI. Types of Events  Below, are some of the many kinds of events, swing components generate. Act causing EventListener Type User clicks.
Event Handling and Listeners in SWING The practice of event handling.
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
UQC117S2 Graphics Programming Lecture 2 Event Handling Program as a sequence of instructions Event -driven program Need to detect the event and carry out.
Sep 181 Example Program DemoTranslateEnglishGUI.java.
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.
1CS480: Graphical User Interfaces. Dario Salvucci, Drexel University. Lecture 6: Event-Driven Programming.
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
TENTH LECTURE Event and listener. Events and Listeners An event can be defined as a type of signal to the program that something has happened. The event.
1 DemoBasic_v3, DemoBasic_v4 JButton JLabel. 2 Registering an ActionListener Register by invoking the following from within constructor DemoBasicFrame.
Prepared by: Dr. Abdallah Mohamed, AOU-KW Unit7: Event-driven programming 1.
Events and Event Handling
Chapter 14 Event-Driven Programming
CompSci 230 S Programming Techniques
CHAPTER Reacting to the user.
Chapter 12 Event-Driven Programming
GUI III IS
GUI Event Handling Nithya Raman.
GUI Programming III: Events
Event-driven programming for GUI
Chapter 16 Event-Driven Programming
Events, Event Handlers, and Threads
Programming Graphical User Interface (GUI)
Making Java GUIs Functional
Presentation transcript:

More Event Handling Adapters Anonymous Listeners Pop menus Validating User Input

Remember event handling.. public class MyWindow extends JFrame implements ActionListener { public MyWindow(){... ok = new JButton("OK"); ok.addActionListener(this); panel.add(ok);... } // event handler public void actionPerformed (ActionEvent e){ System.exit(0); // i.e. what happens }

Examples… User action that results in EventListener Type User clicks a button, presses Enter whileActionListener typing in a text field, chooses a menu item User closes a frame (main window)WindowListener User presses a mouse button while overMouseListener a Component User moves the mouse over a componentMouseMotionListener Component gets the keyboard focusFocusListener Table or list selection changesListSelectionListener Any property in a component changes,PropertyChangeListener such as the text on a button So when designing a GUI, you’ve got to figure out which listeners you need, for what components/user actions

ActionEvents ActionEvents are generated from –a JButton –a JMenuItem –a JTextField (if user presses Enter) All ActionEvents are handled by same event handler public void actionPerformed(ActionEvent e) How to distinguish between components generating the events? –i.e. supposing have 3 buttons, 2 menu items on the same screen? Which one was clicked? –Use the event to determine which component created it getSource() method returns the object that created the event

ActionEvents public void actionPerformed(ActionEvent e) { if (e.getSource() instanceof JButton) { if (e.getSource() == saveButton) { ………………… } else if (e.getSource() instanceof JMenuItem) { if (e.getSource() == newMenuItem) {…………… } else if (e.getSource() instanceof JTextField) { if (e.getSource() == nameTextField {………. } } etc

ActionEvents public void actionPerformed(ActionEvent e){ if (e.getSource() instanceof JButton) { if (e.getSource() == saveButton) {… } else if (e.getSource() instanceof JMenuItem) { if (e.getSource() == newMenuItem){… } else if (e.getSource() instanceof JTextField){ if (e.getSource() == nameTextField{… } Components that the user will interact can be set up as instance variables of the class. Then Can access in the action performed Method. More on code structure later.. public class MyWindow extends JFrame { private JButton saveButton; private JMenuItem newMenuItem; private JTextField nameTextField; public MyWindow(){ … …

Adapters Certain events can be generated by multiple actions, –e.g. opening, closing, minimising, maximising, activating, deactivating a window all create a WindowEvent –e.g. clicking a mouse, moving a mouse over a component, pressing and releasing the mouse buttons all create a MouseEvent the Listener has to handle all actions –many event handlers, one for each type of event (because different things happen as a response to each event…)

Listeners with multiple event handlers Your window may only need to handle one event but as it implements a listener interface it must override all event handler methods..! That’s the rule of implementing interfaces…. WindowListener: windowActivated(WindowEvent e) windowClosed(WindowEvent e) windowClosing(WindowEvent e) windowDeactivated(WindowEvent e) windowDeiconified(WindowEvent e) windowIconified(WindowEvent e) windowOpened(WindowEvent e) MouseListener: mouseClicked(MouseEvent e) mouseEntered(MouseEvent e) mouseExited(MouseEvent e) mousePressed(MouseEvent e) mouseReleased(MouseEvent e) MouseMotionListener: mouseMoved(MouseMotionEvent e) mouseDragged(MouseMotionEvent e)

public class MyWindow extends JFrame implements WindowListener{ //instance variables //constructor //createContentPane //createMenubar //event handlers public void windowActivated(WindowEvent e){ }// do nothing public void windowClosed(WindowEvent e){ }// do nothing windowClosing(WindowEvent e){ //include code here } windowDeactivated(WindowEvent e){ }//do nothing windowDeiconified(WindowEvent e){ } // do nothing windowIconified(WindowEvent e){ }// do nothing windowOpened(WindowEvent e){ }// do nothing} All I want to do is respond to closing a window….

Adapters To facilitate this: –an abstract Adapter class is created which implements empty methods for all event handlers each xxxListener interface has an associated xxxAdapter class E.g. WindowListener has the WindowsAdapter class –the Listener class then becomes a subclass of the Adapter class and overrides only the event handlers of interest –Think of the adapter class as implementing a set of dummy methods to save you work..

Using Adapters... // register window listener with the frame // within the frame’s constructor this.addWindowListener(new MyWindowListener());... // create WindowListener class class MyWindowListener extends WindowAdapter { // override event handler public void windowClosing(WindowEvent e) { // include logic here }

What if you adapter class can’t be used? To use an adapter class, your class has to inherit from it Since java supports single inheritance, can be restrictive – A solution is to use an anonymous listener… But be aware of performance issues – using anonymous listeners, you’re loading an extra class – increases start up time and memory requirements

Anonymous Listeners Listeners can be defined anonymous (i.e. with no name) –Class is created “on the fly” (i.e. placed where it is needed, where the listener is registered with the component) –anonymous  cannot be used by another component –responsible for only a single component  no need to include getSource() etc to identify where the event was generated –Used frequently with WindowListeners.. Why do you think? Syntax is component.addXXXListener( [whole definition of XXXListener goes here] );

Anonymous Listener Example addWindowListener( //begin implementation of Listener new WindowAdapter() { // begin implementation of required method public void windowClosing(WindowEvent e){ // include cleanup code here } // end required method } end Listener ); // end addWindowListener..and relevant method that you want your i/f to respond to is called Adapter class is instantiated. No name…

Pop up menus

PopupMenus Pop-up menus are free floating menus that are associated with an underlying component (the invoker) E.g. right clicking on your mouse as you read this… How would you implement..? Create a menu, decide what makes it appear (e.g. mouse right click ?.. so listen for this and show the menu), say exactly where on screen it should pop up, what events happen when I select menu options, etc.

Brought into existence by a pop-up trigger event that occurs while the mouse is over the invoker –trigger event is platform dependent –normally a MouseEvent –could be mouse pressed or mouse released event Pop-up menu created using JPopupMenu class –JMenuItems and separators added as before Pop-up menu is displayed using show() void show(Component origin, int x, int y) PopupMenus what component is associated with the it, and the location to display it…

Using Popup Menus Create the component – the popup menu –Register listeners with the menu items so you know when user has clicked on them Add event handling for menu items of the popup menu Create a MouseListener (using MouseAdapter) to listen for the trigger (user right click) Add event handling code to display the popup when requested Register MouseListener with appropriate component (normally some container)

Create Popup Menu private JPopupMenu createPopUp(){ // create pop-up menu JPopupMenu popup = new JPopupMenu(); // add menu items and associated listener menuItem = new JMenuItem(“whatever…”); menuItem.addActionListener(myActionListener); popup.add(menuItem); return popup; } Invoke this method in the JFrame constructor to create the popup menu

Create MouseListener that triggers the pop up menu // create PopupListener (a MouseListener) class PopupListener extends MouseAdapter{ JPopupMenu popup;// instance variable PopupListener(JPopupMenu popup){ this.popup = popup; } // include appropriate event handlers // for relevant acions e.g. mousePressed public void mousePressed(MouseEvent e) { if (e.isPopupTrigger()) { popup.show(e.getComponent(), e.getX(), e.getY()); } Note that we’re using an adapter class

Register MouseListener myPopupListener = new PopupListener(popup); Instantiate Listener Register listener with the component that popup is invoked on invoker.addMouseListener(myPopupListener); e.g. the invoker might be a panel..

Validating User Input In GUI user enters text into JTextFields Use String getText() to extract text from field May need to extract numbers from returned String –Use Envelop classes – wrapper classes for each primitive datatype Integer  int int Integer.parseInt(String s) Double  double double Double.parseDouble(String s) Float  float float Float.parseFloat(String s) –Must handle the NumberFormatException

Validating User Input public void actionPerformed (ActionEvent e){ // extract string from textfield String str = field.getText().trim(); try{ // try to extract num from string double num = Double.parseDouble(str); // successfully extracted the number // do something with it... } // unsuccessful extract so handle the error catch (NumberFormatException e){ // display error msg JOptionPane.showMessageDialog(null, "You did not enter a number"); } } An example… Trim() moethod gets rid of leading and trailing whitespaces..

Looked at… Implementing listeners –E..g MouseListener, WindowListener –As interfaces (just implement in your frame) –As adapter classes (when there are many method you don’t need) –As anonymous listeners – when inheriting from adapter class not good.. Creating Pop Menus Example of validating user input –Remember that field text is extracted as a String – convert if needs to be treated as a number…