Chapter 6: Events in Java 1.0 Model –Event class –selecting component to handle –handleEvent method –helper methods (action, keyUp, mouseUp, etc.) 1.1.

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

Programming in Java; Instructor:John Punin Graphics and Graphical User Interfaces1 Programming in Java Graphics and Graphical User Interfaces.
TCU CoSc Programming with Java Handling Events.
Event-Driven Programming You might have realized in creating a GUI and clicking on the JButtons that nothing happens Clicking on a JButton causes the JVM.
Jan Event Handling Yangjun Chen Dept. Business Computing University of Winnipeg.
For Computational Finance Java Applets and the AWT Jeff Stephenson (slides adapted from Manu Kumar)
Jan Event Handling -1.1 Yangjun Chen Dept. Business Computing University of Winnipeg.
June 1, 2000 Object Oriented Programming in Java (95-707) Advanced Topics 1 Lecture 9 Object Oriented Programming in Java Advanced Topics Abstract Windowing.
OOP&M - theory lectures1 OOP&M – the sixth day “… there must be a secret out there …” - Spok -
Event Handling Events and Listeners Timers and Animation.
Event-Driven Programming
Event Handling n Events: an event is an object that describes a state change in a source. n Event Sources: A source is an object that generates an event.
1 Gui Programming (Part I) Graphical User Interfaces (Part I) l Introduction to events. l A Brief history. l Event sources and listeners. l The delegation.
Intermediate Java1 An example that uses inner classes Week Four Continued.
Event Handling. In this class we will cover: Keyboard Events Mouse Events Focus Events Action Interface Multicasting.
Io package as Java’s basic I/O system continue’d.
28-Aug-15 Air Force Institute of Technology Electrical and Computer Engineering Object-Oriented Programming Design Topic : Event Handling – GUI Part II.
Mouse Events. Handling Mouse Events Java provides two listener interfaces to handle mouse events: MouseListener;  MouseListener;  MouseMotionListener.
Graphical User Interface CSI 1101 N. El Kadri. Plan - agenda Graphical components Model-View-Controller Observer/Observable.
Cs884(Prasad)java12AWT1 Abstract Windowing Toolkit Support for Graphical User Interface (Event-driven programming)
CS 11 java track: lecture 4 This week: arrays interfaces listener classes inner classes GUI callbacks.
Dale Roberts GUI Programming using Java - Event Handling Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer.
7/3/00SEM107- © Kamin & ReddyClass 11 - Events - 1 Class 11 - Events r A couple of odds & ends m Component sizes  switch statement r Event types r Catching.
Graphical User Interface Components: Part 1 Chapter 11.
– Advanced Programming P ROGRAMMING IN Lecture 21 Introduction to Swing.
1 Outline 1 Introduction 2 Overview of Swing Components 3 JLabel 4 Event Handling 5 TextFields 6 How Event Handling Works 7 JButton 8 JCheckBox and JRadioButton.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
1 Unit 5 GUI Aum Amriteshwaryai Namah. 2 Overview Shall learn how to reuse the graphics classes provided by Java for constructing Graphical User Interface.
MSc Workshop - © S. Kamin, U.Reddy Lect 4 - Events - 1 Lecture 4 – Event Handling r Painting r Event types r Catching different event types.
12/5/00SEM107, Kamin & ReddyReview - 34 Events Event types Catching different event types Getting information from components and events Distinguishing.
Layout Managers Arranges and lays out the GUI components on a container.
Omer Boyaci.  GUIs are event driven.  When the user interacts with a GUI component, the interaction—known as an event—drives the program to perform.
Pravin Yannawar, DOCS, NMU Jalgaon. Basic Java : Event handling in AWT and Swing 2 Objectives of This Session Explain the Event handling mechanism & demonstrate.
1 / 67 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 14 Programming Fundamentals using Java 1.
© 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.
Universidad Nacional de Colombia Facultad de Ingeniería Departamento de Sistemas ertificación en AVA.
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.
Week 6: Basic GUI Programming Concepts in Java Example: JFrameDemo.java container : a screen window/applet window/panel that groups and arranges components.
Object Oriented Programming.  Interface  Event Handling.
Event Handling. The signals that a program receives from the operating system as a result of the actions are called events. A window based program is.
Agenda Introduction. Event Model. Creating GUI Application. Event Examples.
Index Event Handling Events Event Source Event Listener Event Classes Action Event Class Adjustment event Class Event Source Event Listener Interface Using.
Events in JAVA Needed for Applets and GUI based programs. Applet uses GUI to interact with user. Most of the events are generated by Mouse, Keyboard.
Graphical User Interfaces (GUI). PART ONE About GUI’s.
 Many event-listener interfaces contain multiple methods.  An adapter class implements an interface and provides a default implementation (with an empty.
Events (Chapter 11) Java Certification Study Group January 25, 1999 Mark Roth.
2/17/2016 DEPT OF CSE 1 EVENT HANDLING. 2/17/2016 DEPT OF CSE 2 Event handling is at the core of successful applet programming There are several types.
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.
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.
Event Handling and Listeners in SWING The practice of event handling.
Sep 181 Example Program DemoTranslateEnglishGUI.java.
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.
Java Programming (By Rama Bhadra Rao M) You can Trace me in Day 5
Dept. of CSIE, National University of Tainan 10/21/2012 Responding to User Input.
GUI Programming in Java Hao Jiang Boston College April, 2009.
CSC 205 Programming II Lecture 5 AWT - I.
Events and Event Handling
Chapter 14 Event-Driven Programming
Lecture 8 Object Oriented Programming Using Java
Programming in Java, 2e Sachin Malhotra Saurabh Choudhary.
CHAPTER Reacting to the user.
Chapter 12 Event-Driven Programming
Programming in Java Sachin Malhotra, Chairperson, PGDM-IT, IMS Ghaziabad Saurabh Chaudhary, Dean, Academics, IMS Ghaziabad.
Event Handling Chapter 2 Objectives
Programming in Java Event Handling
Web Design & Development Lecture 12
Making Java GUIs Functional
Presentation transcript:

Chapter 6: Events in Java 1.0 Model –Event class –selecting component to handle –handleEvent method –helper methods (action, keyUp, mouseUp, etc.) 1.1 Model –Listeners - connected to Event generatorsEvent types: ActionEvent, ItemEvent, etc. –corresponding Listeners: ActionListener, etc. –connecting generator to listener –Interfaces and Adapters

Abstract Classes Class may be abstract by adding modifier in class header public abstract class MyClass Resulting class cannot be instantiated Used to create general classes (Car) that you expect to specialize

Interfaces A class may only inherit from one parent Sometimes want to create specialized class, combines several capabilities Interface is a list of methods to instantiate public interface Drawable { public void draw() {} // empty body } Class header, indicate implements interface public class Rect extend GObj implements Drawable; must implement all methods of interface may have more than one interface

Event-Driven Programming Input “events” by the user caught by Java –move mouse, click button, scroll window, type key For each, Java creates an Event object Object added to queue, your program is then expected to “handle” the events

1.0 Event Model Event object: instance vars: Object target - which object generated the event int id - a value indicating the type of event Object arg - useful info about the event (dependent) long when - time of event int x - x location of event int y - y location of event int clickCount - number of times button clicked int key - key pressed (for key events) int modifiers - for key and mouse events

Event id Constants ACTION_EVENT - Buttons, Checkboxes, Choices, Lists, MenuItems, TextFields KEY_PRESS, KEY_RELEASE, KEY_ACTION, KEY_ACTION_RELEASE MOUSE_DOWN, MOUSE_UP, MOUSE_DRAG, MOUSE_MOVE, MOUSE_ENTER, MOUSE_EXIT - mouse LIST_SELECT, LIST_DESELECT - List events SCROLL_ABSOLUTE, SCROLL_LINE_UP, SCROLL_LINE_DOWN, SCROLL_PAGE_UP, SCROLL_PAGE_DOWN WINDOW_EXPOSE, WINDOW_ICONIFY, WINDOW_DEICONIFY, WINDOW_DESTROY, WINDOW_MOVED LOAD_FILE, SAVE_FILE GOT_FOCUS, LOST_FOCUS

Handling Events Java does lots of stuff for you (keys in Text objects, window moves, etc.) You add handling events for things you want handled a particular way, or when no obvious method (what to do when button pushed)

Source of the Event Java sends event to Component it thinks is responsible Component should –handle event and stop –pass event its parent class –say it can’t handle event (pass to parent in GUI) –handle event and pass on (rare) Java will automatically pass event to parent in GUI hierarchy if not handled –for Button, Comp (e.g. Panel) contains Button

Event-Handling Methods Every component has handleEvent method public boolean handleEvent(Event e) { if (e.id == Event.WINDOW_DESTROY) { System.exit(0); return true; }} Return value indicates if handled –true - event handled, terminate –false - event not completely handled, try someone else (parent in GUI hierarchy)

Passing On Events Sometimes we handle some events, want to pass it on to others: public boolean handleEvent(Event e) { if (e.id == Event.WINDOW_DESTROY) { … } else return super.handleEvent(e); } Give the next Component up in the class hierarchy the chance to handle event

Helper Methods handleEvent rarely used Java provides “helper” methods specific to particular types of events –can be implemented instead of handleEvent –called after handleEvent tried –action events - actions –key events - keyDown, keyUp –mouse events - mouseDown, mouseUp, mouseDrag, mouseMove, mouseEnter, mouseExit

action Method form: public boolean action (Event e, Object arg) {} used for many widgets: –Button e.target is button obj, arg is string name of button –Checkbox e.target is Cb obj, arg is check value (true or false) –Choice, List e.target is choice obj, arg is string of choice made

Helper Calling Parent As with handleEvent, if helper fails to handle event, should call superclass action: –return super.action(e,arg) Return values have same meaning as in handleEvent

key Methods form: public boolean keyUp (Event e, int key) {} public boolean keyDown(Event e, int key) {} key is char pressed –modifiers field indicates if Shift, Alt, Meta, or Control held while pressed –check with constants SHIFT_MASK, META_MASK, CONTROL_MASK (e.modifiers & Event.SHIFT_MASK) or e.shiftDown() also has metaDown and controlDown, but none for Alt –other keys (Functions like F1) use Action Key events, Java has constants for such (Event.F1)

mouse Methods form: public boolean method(Event e, int x, int y) {} methods: mouseUp, mouseDown, mouseMove, mouseDrag, mouseEnter, mouseExit x, y are locations of occurrence –modifiers used to indicate if left, right, center –no modifiers: left –meta set: right –alt set: center

import java.applet.*; import java.awt.*; public class TestAction extends Applet { Button button = new Button("AButton"); Checkbox cbox1 = new Checkbox("CB1"); Checkbox cbox2 = new Checkbox("CB2"); CheckboxGroup cbg = new CheckboxGroup(); Choice choice = new Choice(); Panel panel = new Panel(); MyCanvas canvas = new MyCanvas(); public void init () { panel.setLayout(new GridLayout(2,2)); cbox1.setCheckboxGroup(cbg); cbox2.setCheckboxGroup(cbg); choice.addItem("Item1"); choice.addItem("Item2"); choice.addItem("Item3"); panel.add(cbox1); panel.add(cbox2); panel.add(button); panel.add(choice); panel.layout(); setLayout(new GridLayout(2,1)); add(panel); add(canvas); }

public boolean action (Event e, Object arg) { if (e.target == button) { canvas.setMessage(arg + " pressed"); } else if ((e.target == cbox1) || (e.target == cbox2)) { Checkbox tempcb = (Checkbox) e.target; canvas.setMessage(tempcb.getLabel() + " checked"); } else if (e.target == choice) { canvas.setMessage(arg + " chosen"); } return true; } class MyCanvas extends Canvas { private String theMessage = “”; public MyCanvas() { resize(500,40); } public void paint(Graphics g) { g.drawString(theMessage,10,30); } public void setMessage(String s) { theMessage = s; repaint(); }

1.0 to the 1.1 Delegation Model Event generators tend to be scattered in 1.0 Handlers often centralized Difficult to write good general handlers Idea: connect generators with appropriate handlers

The Delegation Model (1.1) Any object can be a source of an Event Any object can listen for events –implement (register) an appropriate listener interface –listeners stay close to generators Need to import java.awt.event.*

General methods Object getSource() - generator of event, from EventObject int getID() - constant for type of event (useful for some Mouse or Key events) - from AWTEvent

Handling Events For different types of events we have –an Event class (with useful methods) –an EventListener interface with required methods that must be implemented as part of listener –after creating instance of class that can generate events, connect to appropriate listener interface use addListenerType(Object generator) methods

Action Events click Button, double-click member in List, select MenuItem, press in TextField ActionEvent methods: –String getActionCommand() - string for source button - label list, menuitems - text of selected item textfield - content of textfield –int getModifiers() - use to check if modifiers set Listener: ActionListener –methods: void actionPerformed(ActionEvent e)

Item Events Select Checkbox, CheckboxMenuItem, Choice item, or single-click List item ItemEvent methods: –Object getItem() - item selected (usually String) –int getStateChange() - returns value of state ItemEvent.SELECTED or ItemEvent.DESELECTED –ItemSelectable getItemSelectable() - return ItemSelectable object that generated event Listener: ItemListener –methods: void itemStateChanged(ItemEvent e)

Input Events Abstract class for Key and Mouse Events Has constants for masks: ALT_MASK, etc. Also has boolean methods: –boolean isAltDown() –boolean isControlDown() –boolean isMetaDown() –boolean isShiftDown() Other method: int getModifiers()

Mouse Events MouseEvent, MouseMovedEvent methods: –int getX() - x location of mouse event –int getY() - y location of mouse event –Point getPoint() - x,y location –int getClickCount() - number of clicks Listeners: –MouseListener - for click, press, enter, exits methods: –void mouseClicked(MouseEvent e) –mousePressed, mouseReleased, mouseEntered, mouseExited –MouseMotionListener - for drag, move methods: –void mouseMoved(MouseMovedEvent e) –void mouseDragged(MouseMovedEvent e)

Key Events KeyEvent methods: –char getKeyChar() - char of key pressed –boolean isActionKey() - true if action key –int getKeyCode() - code for action keys –void setKeyChar(char c) - set char in event –void setKeyCode(int keyCode) - set keyCode Listener: KeyListener –Methods: void keyPressed(KeyEvent e) void keyReleased(KeyEvent e) void keyTyped(KeyEvent e)

Text Events Changes to TextField or TextArea Listener: TextListener –methods: void textValueChanged(TextEvent e)

Adapters To implement an interface you must implement ALL methods of interface –even if only an empty method Alternate solution: extend an Adapter (interface with empty methods): –MouseAdapter –MouseMotionAdapter –KeyAdapter

General Use of Listener in declaring generator: private Widget myWidget = new Widget(); private ApropListClass myListener; in init or constructor: myListener = new ApropListClass(myWidget); myWidget.addApropListener(myListener) new class: class ApropListClass implements ApropListener { private Widget copyWidget; public ApropListClass(Widget w) { copyWidget = w; } public void apropListenerMethod(Item e) { // implement }

import java.applet.*; import java.awt.*; import java.awt.event.*; public class TestAction extends Applet { Button button = new Button("AButton"); private AButtonListener myButtonListener; Checkbox cbox1 = new Checkbox("CB1"); private ACheckboxListener myCB1Listener; Checkbox cbox2 = new Checkbox("CB2"); private ACheckboxListener myCB2Listener; CheckboxGroup cbg = new CheckboxGroup(); Choice choice = new Choice(); private AChoiceListener myChoiceListener; Panel panel = new Panel(); MyCanvas canvas = new MyCanvas();

public void init () { myButtonListener = new AButtonListener(button,canvas); button.addActionListener(myButtonListener); myCB1Listener = new ACheckboxListener(cbox1,canvas); cbox1.addItemListener(myCB1Listener); myCB2Listener = new ACheckboxListener(cbox2,canvas); cbox2.addItemListener(myCB2Listener); myChoiceListener = new AChoiceListener(choice,canvas); choice.addItemListener(myChoiceListener); panel.setLayout(new GridLayout(2,2)); cbox1.setCheckboxGroup(cbg); cbox2.setCheckboxGroup(cbg); choice.addItem("Item1"); choice.addItem("Item2"); choice.addItem("Item3"); panel.add(cbox1); panel.add(cbox2); panel.add(button); panel.add(choice); panel.validate(); setLayout(new GridLayout(2,1)); add(panel); add(canvas); }

class AButtonListener implements ActionListener { Button buttonCopy; MyCanvas canvasCopy; public AButtonListener(Button bcopy, MyCanvas ccopy) { buttonCopy = bcopy; canvasCopy = ccopy; } public void actionPerformed(ActionEvent e) { canvasCopy.setMessage(buttonCopy.getLabel() + " pressed"); } class ACheckboxListener implements ItemListener { Checkbox checkboxCopy; MyCanvas canvasCopy; public ACheckboxListener(Checkbox cbcopy, MyCanvas ccopy) { checkboxCopy = cbcopy; canvasCopy = ccopy; } public void itemStateChanged(ItemEvent e) { canvasCopy.setMessage(checkboxCopy.getLabel() + ” checked"); }

class AChoiceListener implements ItemListener { Choice choiceCopy; MyCanvas canvasCopy; public AChoiceListener(Choice chcopy, MyCanvas ccopy) { choiceCopy = chcopy; canvasCopy = ccopy; } public void itemStateChanged(ItemEvent e) { canvasCopy.setMessage(choiceCopy.getSelectedItem() + ” chosen"); } class MyCanvas extends Canvas { private String theMessage = ""; public MyCanvas() { setSize(500,40); } public void paint(Graphics g) { g.drawString(theMessage,10,30); } public void setMessage(String s) { theMessage = s; repaint(); }