Graphical User Interface (GUI) Programming II. Lecture Objectives Understand the Event-Handling Processes in Java.

Slides:



Advertisements
Similar presentations
1 Graphical User Interface (GUI) Applications Abstract Windowing Toolkit (AWT) Events Handling Applets.
Advertisements

Introduction to Java 2 Programming
Unit 091 Introduction to GUI Programming Introduction to User Interfaces Introduction to GUI Programming GUI Design Issues GUI Programming Issues Java.
Event-Driven Programming Thus far, our programs have been executed one statement after the other However, many programs depend on user actions to dictate.
1 Chapter 7 Graphics and Event Handling. 2 Overview The java.awt and javax.swing packages and their subpackages support graphics and event handling. Many.
Graphical User Interface (GUI) Programming II. Lecture Objectives Understand the Event-Handling Processes in Java.
Event Handling. In this class we will cover: Basics of event handling The AWT event hierarchy Semantic and low-level events in the AWT.
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.
Object Oriented Programming Java 1 GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann GUI Programming.
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.
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.
PROGRAMMING REVIEW Lab 2 EECS 448 Dr Fengjun Li and Meenakshi Mishra.
Java Programming Chapter 10 Graphical User Interfaces.
Events Here, we review event handling one more time. To understand how events work in Java, we have to look closely at how we use GUIs. When you interact.
Applets and Frames CS 21a: Introduction to Computing I First Semester,
Nota Bene This lecture presentation contains a number of "hidden" slides. Feel free to read, study and learn from them on your own! (I openned them all)
Graphical User Interface CSI 1101 N. El Kadri. Plan - agenda Graphical components Model-View-Controller Observer/Observable.
More Event Handling Adapters Anonymous Listeners Pop menus Validating User Input.
Copyright © 2002, Systems and Computer Engineering, Carleton University Gui1.ppt * Object-Oriented Software Development Part 18 Building.
Objectives of This Session
Session 27 Swing vs. AWT. AWT (Abstract Window ToolKit) It is a portable GUI library for stand-alone applications and/or applets. The Abstract Window.
GUIs in Java Swing, Events CS2110, SW Development Methods Readings: MSD, Chapter 12 Lab Exercise.
1 CSC111H Graphical User Interfaces (GUIs) Introduction GUIs in Java Understanding Events A Simple Application The Containment Hierarchy Layout Managers.
– 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.
GUI Clients 1 Enterprise Applications CE00465-M Clients with Graphical User Interfaces.
Graphics and Event-Driven Programming in Java John C. Ramirez Department of Computer Science University of Pittsburgh.
MSc Workshop - © S. Kamin, U. ReddyLect 3 - GUI -1 Lecture 3 - Graphical User Interfaces r GUI toolkits in Java API r JFrame r GUI components.
Applets and Frames. Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L14: GUI Slide 2 Applets Usually.
Pravin Yannawar, DOCS, NMU Jalgaon. Basic Java : Event handling in AWT and Swing 2 Objectives of This Session Explain the Event handling mechanism & demonstrate.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Lec.10 (Chapter 8 & 9) GUI Jiang (Jen) ZHENG June 27 th, 2005.
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
Java GUI. Graphical User Interface (GUI) a list a button a text field a label combo box checkbox.
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.
Object Oriented Programming.  Interface  Event Handling.
Ch13 Creating windows and applets. Short overview AWT (Abstract Windowing Toolkit) Early Java development used graphic classesEarly Java development used.
CIS Intro to JAVA Lecture Notes Set 8 9-June-05.
Basics of GUI Programming Chapter 11 and Chapter 22.
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.
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.
Lesson 28: More on the GUI button, frame and actions.
Sep 181 Example Program DemoTranslateEnglishGUI.java.
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
1 DemoBasic_v3, DemoBasic_v4 JButton JLabel. 2 Registering an ActionListener Register by invoking the following from within constructor DemoBasicFrame.
1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:
Prepared by: Dr. Abdallah Mohamed, AOU-KW Unit7: Event-driven programming 1.
A Quick Java Swing Tutorial
Lecture 15 Basic GUI programming
CSC 205 Programming II Lecture 5 AWT - I.
Graphical User Interfaces
Welcome To java
CHAPTER Reacting to the user.
A First Look at GUI Applications
University of Central Florida COP 3330 Object Oriented Programming
Graphical User Interface (GUI) Programming II
A Quick Java Swing Tutorial
GUI Event Handling Nithya Raman.
GUI Programming III: Events
Event-driven programming for GUI
A Quick Java Swing Tutorial
Events, Event Handlers, and Threads
Programming Graphical User Interface (GUI)
Graphical User Interface
Presentation transcript:

Graphical User Interface (GUI) Programming II

Lecture Objectives Understand the Event-Handling Processes in Java

Caution Note!!! This lecture presentation contains a number of "hidden" slides. Feel free to read, study and learn from them on your own!!!

Outline for Today's Fun Events:  What is an event?  Simple (?) Example Swing Components:  JFrames  JComponents  An example  Swing Component Design (MVC/UI-Delegate??)

Events Behind the scenes, the Java runtime environment is monitoring many things When any of a number of things happen an event is said to occur. Sometimes the terminology is “an event gets fired“ Examples of the types of things that can "fire" events:  Pressing a key on the keyboard  Clicking on a component (like a button)  Entering a component with the mouse pointer  Have a timer "time-out"

Moving the mouse around any reasonably complicated GUI can literally cause hundreds if not thousands of events to occur. Events will be ignored except for the ones that you tell Java that you are interested in doing something about. Java maintains a data structure of all the events that you have decided to handle and looks up events and does what you tell it to do. Events (Cont’d)

Code from the Past: Remember??? import java.awt.*; public class HelloGUI { public static void main (String[ ] args) { System.out.println("About to make GUI"); Frame f = new Frame ("Hello GUIs"); f.setSize( 200, 200 ); f.show(); System.out.println("Finished making GUI"); }// main }// class HelloGUI

What didn't work??? Code from the Past: Remember???

Making It Work (MIT Approach)! Determine which event occurs when the "Close the Window" button is pressed:  The API is your friend  The lecture notes are your friend  Hint: In this case it's an event called "Window Closing" You decide what class is going to handle this event  It might be the actual class which has the window.  It can be any other class.

Making It Work (MIT Approach)! Write the method (and class?) that will handle the event: When this event occurs, Java is going to go to the class that you identify as the event handler or Listener. It will look for a method called: public void windowClosing(WindowEvent e) Java will report an error to you if this class doesn't have this method. How might the designers of Java be guaranteed that you will implement this method?

Interfaces: Back to School! // Note: found in java.awt.event public interface WindowListener extends EventListener { void windowActivated(WindowEvent e); void windowClosed(WindowEvent e); void windowClosing(WindowEvent e); void windowDeactivated(WindowEvent e); void windowDeiconified(WindowEvent e); void windowIconified(WindowEvent e); void windowOpened(WindowEvent e); }

So we could write a class as shown below: import java.awt.*; import java.awt.event.*; public class Handler implements WindowListener { public void windowActivated(WindowEvent e) {} public void windowClosed(WindowEvent e) {} public void windowClosing(WindowEvent e) { Window w = e.getWindow(); w.setVisible(false); w.dispose(); System.exit(0); } public void windowDeactivated(WindowEvent e) {} public void windowDeiconified(WindowEvent e) {} public void windowIconified(WindowEvent e) {} public void windowOpened(WindowEvent e) {} } Using Event Interfaces Outline: Import Class definition Implementation Dummy (lazy) implementation

Register the listener with Java. That is, tell Java in which class the method will be located to run when the Window Closing Event occurs. Using Event Interfaces (Cont’d)

Event Handler Registration import java.awt.*; public class HelloGUI { public static void main (String[] args) { Handler h = new Handler(); System.out.println ("About to make GUI"); Frame f = new Frame ("Hello GUIs"); f.setSize( 200, 200 ); f.addWindowListener(h); f.show(); System.out.println("Finished making GUI"); } // main } // class HelloGUI

Demonstration Class Pool class HelloGUI main { Frame f Handler h } class Frame class Handler Frame Instance Handler Instance Interface WindowListener

Event Handling: Key Ideas 1.Determine which event occurs 2.Decide what class is going to handle this event 3.Write the method (and class?) that will handle the event. 4.Register the listener with Java.

Today’s First Wisdom Very important that you understand this simple example to understand the concepts that follow.

Potential Points of Confusion What exactly is the listener? Is it the component getting clicked on?  No, the listener is the object that contains the method that Java will call when the event happens.  You must tell the component getting clicked which object that is by registering: addWindowListener...  As we will see it could be the same!!! What type of listener do I use?  There are only so many.  See the Java API.  Lecture/Instructor/Lab/WebCT/Classmates/Friends.  Try yourself and experience the excitement!

Potential Points of Confusion (Cont’d) What about all those other window things (e.g. windowActivated)  We actually did implement them (with empty bodies) – Lazy or dummy implementation!  We said: Don't do anything!

Events:  What is an event?  Simple (?) Example Swing Components:  JFrames  JComponents  An example  Swing Component Design (MVC/UI-Delegate) Outline for Today's Fun: Reminder

A Call from the Past! Earlier, we cautioned about the existence of two toolkits in Java for creating GUIs: AWT Swing Today, we examine a few Swing components. The goal is to learn how Swing components in general are designed, so that you can make better use of the API.

Swing: Sun’s Response to Microsoft? In 1997, Sun announced a new graphical toolkit for Java called the “Java Foundation Classes”, or “JFC”. This is usually called “Swing”. The JFC/Swing classes provide well designed, powerful widgets for GUI developers. Let’s take a look...

Welcome to JFC/Swing Planet “Now it gets interesting... “

Historical Problems with AWT All AWT components required runtime peer resources:  Slow on some platforms (notably Windows)  Portability problems (slightly different look, some behaviors different)  Least common denominator phenomenon: If one OS (e.g., Windows) did not support a widget, the entire AWT had to suffer without it. Limited AWT widget library  Addressed somewhat by JDK 1.1b3+, which allowed subclassing of components, or “lightweights” (not covered in this course) java.awt.Button WinNT ButtonPeer MacOS ButtonPeer Motif ButtonPeer AWT components required native “peer” methods to render and operate--many steps! CLICK ME File Edit Help Slow & Inflexible!

Developers avoided a few AWT limitations through:  Pervasive use of lightweights (again, not covered in cs1312).  e.g., tooltip simulation through threads/windows/components  extensive coding around rigid look  use of layered gifs CLICK ME File Edit Help Tooltip (Tooltips required threads, window subclasses & extensive event handling) (Image buttons required component subclassing, methods to handle ‘click’ look, as well as event handlers) (Menu bars limited; no images possible without *extensive* simulation through components) (Layering of components requires layout subclasses) Bottom line: Making stuff look cool or satisfying a client’s request could be a nightmare! Bottom line: Making stuff look cool or satisfying a client’s request could be a nightmare! Fixing AWT Problems

Introducing Swing/JFC Sun addressed these problems by producing Java Foundation Classes (JFC) i.e., Swing Key elements:  No reliance on native peers; the JVM does the work, and is faster  Swing completely controls look and feel of all components: PLAF, or “pluggable look and feel”  Superior design: MVC-esque (Model View Control) javax.swing.JButton Fast, flexible, extensible! CLICK ME File Edit Help

javax.swing.* Swing Packages All the new Swing components and classes need a home. Where? A subject of great debate! For JDK 1.1, Sun used “com.sun.java.swing”; developers revolted. Problem: developers complained this “com” designation was not appropriate for “core” class--something part of language. Solution: Denotes ‘extension’ package that has migrated to core status Why “javax”? * logical grouping * minimizes transition costs * most developers happy with it * helps maintain existing JDK 1.1 code (cf. MFC lib breaks)

Overview of JFC/Swing Packages javax.swing.plaf javax.swing.plaf.basic javax.swing.plaf.metal javax.swing.plaf.multi javax.swing.text javax.swing.text.html javax.swing.text.html.parser javax.swing.text.rtf javax.swing javax.swing.table javax.swing.tree javax.swing.border javax.swing.colorchooser javax.swing.filechooser javax.swing.event javax.swing.undo

Overview of the Overview Text-based widgets (including html/rtf display) New event packages Components, including “aggregate” or complex components Packages to control the “look and feel” of Swing

Short Examples1.

Short Example: Old AWT We comment most of this out for now; AWT lets us add directly to the Frame. import java.awt.*; public class HelloWorld extends Frame { public Button bOld; //public Panel p; public HelloWorld() { bOld = new Button ("Good Bye"); //p = new Panel(); //p.add(bOld); //this.add(p); this.add(bOld); /* note the addition directly to the Frame */ this.pack(); } public static void main(String arg[]){ /* note lack of listener; this is a demo */ new HelloWorld().show(); } }// class HelloWorld

Hello Swing, Good Bye AWT! Note addition of components to JPanel’s ‘content pane’ Note Swing components SEE CAUTIONARY NOTE RE: Mixing light and heavyweight components!!! import java.awt.*; import java.awt.event.*; import javax.swing.*; public class HelloWorld extends JFrame { Button bOld; public JButton bNew; public JPanel p; public HelloWorld() { bNew = new JButton("Hello"); bOld = new Button ("Good Bye"); p = new JPanel(); p.add(bNew); p.add(bOld); this.getContentPane().add(p); this.pack(); } public static void main(String arg[]){ new HelloWorld().show(); } }// class HelloWorld

What’s the Big Deal? HelloWorld looks similar to AWT. Why switch to JFrame, JButton, JPanel, etc? Benefits:  speed  lightweight flexibility (transparency, non-rectangular shape)  pluggable look and feel  automatic double buffering with many J- components.  additional functionality (e.g., tooltips, etc.) I need Windows™ to be visible and ‘toggle’. I’m slow. I’m lightweight, pluggable, extensible and fast. The VM draws me.

Widget Example: JButtons The java.swing.JButton class implements a “state version” of a java.swing.AbstractButton. Many methods come from the abstract class:  A variety of constructors ( Strings, Icons, etc.);  setRolloverEnabled(boolean);  setIcon(Icon);  setRolloverIcon(Icon);  setActionCommand(String); -- an extra String tacked onto the event that gets fired!  setContentAreaFilled(boolean) -- transparency for icons!  setModel(ButtonModel); -- sets the ‘type’ of Button (you can define your own Button behaviors!)  setMnemonic(char/int); -- set mnemonics for button Lesson: Check the API for useful behaviors.

import javax.swing.*; public class HelloWorld2 extends JFrame { public JButton bNew; public JPanel p; public HelloWorld2() { bNew = new JButton("New Document", new ImageIcon("Document.gif")); bNew.setRolloverEnabled(true); bNew.setRolloverIcon(new ImageIcon("New.gif")); p = new JPanel(); p.add(bNew); getContentPane().add(p); this.pack(); } public static void main(String arg[ ]) { new HelloWorld2().show(); } }// class HelloWorld2 Cool Buttons Sets icon and rollover Icon. Note: Icon constructor took String argument, and automatically loaded image Images from disk:

Why getContentPane() ? The HelloWorld example required us to call getContentPane() before “ add() ”ing an object to the JFrame : Usually “ this ” E.g., “ myJButton ” This differs from traditional AWT container additions, where we simply call “ add ”, passing in the component. Let’s cut a JFrame open to find out why... Required of JFrame, JDialog and JInternalFrame instances myFrameInstance.getContentPane().add(myComponent);

A JFrame Autopsy click A java.awt.Frame is composed of a single container--the Frame object itself. It is flat as a pop tart. click JLayeredPane JPanel ContentPane Menu A javax.swing.JFrame is composed of a transparent “glassPane” surface, and an inner JPanel with Contents and Menu “The Pop Tart / Sandwich Duality”

JFrame Class View JRootPane JMenuBar JLayeredPane JFrame Container Component ContentPane GlassPane manages contains JComponent Frame The JRootPane is a container with a JLayeredPane (holding the Menu and ContentPane) and a Component GlassPane. It serves as base for numerous classes. contains AWT JFC

JRootPane: The Content Pane The JRootPane contains only two components: the JLayeredPane and the Component GlassPane Its layout manager ignores all attempts to add new components. Instead, one must add to the JRootPane’s ContentPane, found inside the JLayeredPane. A call to getContentPane() returns an instance of the ContentPane.

JFrame Blue Print We can use the top “glassPane” as a drawing area. Since it spans the entire JFrame, we can draw on top of menu bars, and every component. The JPanel has a remarkable layering feature, allowing us to stack and shuffle components. public Component getGlassPane(); public void setGlassPane(Component); public JPanel getContentPane(); JRootPane: The Glass Pane

JFrame Disposal JFrame allows you to configure how it responds to closure.  Default: hides JFrame on closure attempt.  To modify: invoke setDefaultCloseOperation().  E.g.,: MyJFrameInstance.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ ON_CLOSE); /* behaves just like java.awt.Frame */  other constants in javax.swing.WindowConstants :  HIDE_ON_CLOSE - invokes any registered WindowListener object, then hides. This is default behavior.  DISPOSE_ON_CLOSE - invokes any registered WindowListener object, and then disposes.

JComponent: The Generic Widget The JComponent provides the basis for all Swing components. JComponent extends java.awt.Container, making all Swing components large, powerful widgets. (Also, all Swing components are also containers--even if you wouldn’t normally place things in them. E.g., JButton ) In turn, JComponent is subclassed by numerous widgets. Thus, composition is favored over inheritance for widget manipulation.

Jcomponent (Cont’d) Since JComponent is the basis for most Swing components, all Swing widgets have the following general features: Borders -- JComponent derived classes can have borders Accessibility -- JComponent s use Swing’s accessibility features to provide additional information about the widget. Tooltips -- JComponent s can have time sensitive tooltips. Double Buffering -- By default, Swing components have double buffering built in Serialization -- Ability to save state to a file.

Demo: A GlassPane Example import java.awt.*; import java.awt.event.*; import javax.swing.*; public class GlassDemo extends JFrame implements ActionListener { private boolean bGlassVisible; private GlassPanel glass; private JButton button; Here’s a simple example that shows how to use aspects of JFrames. Frist, we make a JFrame subclass. We declare some instance variables: a GlassPanel (described later), a boolean flag for the glass panel’s visibility, and a JButton to toggle This demo will not be covered in class; it is provided as an example of how to work with JFrames.

import java.awt.*; import java.awt.event.*; import javax.swing.*; public class GlassDemo extends JFrame implements ActionListener { private boolean bGlassVisible; private GlassPanel glass; private JButton button; public void actionPerformed (ActionEvent e){ bGlassVisible = !bGlassVisible; glass.setVisible(bGlassVisible); } The actionPerformed method merely toggles the visibility of the glass pane Demo: A GlassPane Example (Cont’d)

import java.awt.*; import java.awt.event.*; import javax.swing.*; public class GlassDemo extends JFrame implements ActionListener { private boolean bGlassVisible; private GlassPanel glass; private JButton button; public void actionPerformed (ActionEvent e){ bGlassVisible = !bGlassVisible; glass.setVisible(bGlassVisible); } public void centerInScreen(){ Toolkit tk = Toolkit.getDefaultToolkit(); Dimension d = tk.getScreenSize(); this.setLocation((d.width-getSize().width)/2, (d.height-getSize().height)/2); }... A little magic. (It merely centers the frame in the screen.) Demo: A GlassPane Example (Cont’d)

import java.awt.*; import java.awt.event.*; import javax.swing.*; public class GlassDemo extends JFrame implements ActionListener { private boolean bGlassVisible; private GlassPanel glass; private JButton button; public void actionPerformed (ActionEvent e){ bGlassVisible = !bGlassVisible; glass.setVisible(bGlassVisible); } public void centerInScreen(){ Toolkit tk = Toolkit.getDefaultToolkit(); Dimension d = tk.getScreenSize(); this.setLocation((d.width-getSize().width)/2, (d.height-getSize().height)/2); } public static void main(String[] args) { new GlassDemo().show(); } A simple test main() Demo: A GlassPane Example (Cont’d)

public GlassDemo () { this.setSize(400,400); this.getContentPane().setBackground(Color.white); this.getContentPane().setLayout(new BorderLayout()); this.addWindowListener (new WindowAdapter(){ public void windowClosing(WindowEvent e){ System.exit(0); }}); Our constructor has poor abstraction, but is sufficient for a demonstration. We start by setting a size, background, layout, and a simple WindowListener Demo: A GlassPane Example (Cont’d)

public GlassDemo () { this.setSize(400,400); this.getContentPane().setBackground(Color.white); this.getContentPane().setLayout(new BorderLayout()); this.addWindowListener (new WindowAdapter(){ public void windowClosing(WindowEvent e){ System.exit(0); }}); JPanel p = new JPanel(); p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS)); button = new JButton ("Toggle"); button.addActionListener(this); p.add(Box.createHorizontalGlue()); p.add(button); p.add(Box.createHorizontalGlue()); We add a JButton to a containing JPanel. We make sure it will center in the JPanel, using ‘glue’ objects. The same effect can be obtained with more complicated layerings of panels and layout managers. Demo: A GlassPane Example (Cont’d)

public GlassDemo () { this.setSize(400,400); this.getContentPane().setBackground(Color.white); this.getContentPane().setLayout(new BorderLayout()); this.addWindowListener (new WindowAdapter(){ public void windowClosing(WindowEvent e){ System.exit(0); }}); JPanel p = new JPanel(); p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS)); button = new JButton ("Toggle"); button.addActionListener(this); p.add(Box.createHorizontalGlue()); p.add(button); p.add(Box.createHorizontalGlue()); this.getContentPane().add(p, BorderLayout.CENTER); this.getContentPane().add(new JLabel("Press Button to Toggle Glass Pane"), BorderLayout.SOUTH); We add the panel to our JFrame ’s content pane, along with a simple label... Demo: A GlassPane Example (Cont’d)

public GlassDemo () { this.setSize(400,400); this.getContentPane().setBackground(Color.white); this.getContentPane().setLayout(new BorderLayout()); this.addWindowListener (new WindowAdapter(){ public void windowClosing(WindowEvent e){ System.exit(0); }}); JPanel p = new JPanel(); p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS)); button = new JButton ("Toggle"); button.addActionListener(this); p.add(Box.createHorizontalGlue()); p.add(button); p.add(Box.createHorizontalGlue()); this.getContentPane().add(p, BorderLayout.CENTER); this.getContentPane().add(new JLabel("Press Button to Toggle Glass Pane"), BorderLayout.SOUTH); centerInScreen(); glass = new GlassPanel(); this.setGlassPane(glass); bGlassVisible = false; } } // end of class GlassDemo We then make and set a new glass panel for the JFrame. Demo: A GlassPane Example (Cont’d)

Example Output After a press, the glass pane becomes visible.

Events Here, we review event handling one more time. To understand how events work in Java, we have to look closely at how we use GUIs. When you interact with a GUI, there are many events taking place each second. Only a few of these, however, may actually be ‘delivered’ to the application.

Java uses a “delegation” event model found in many other toolkits. Under the delegation model, components fire events, which can be caught and acted on by listeners. A listener is linked to a component through a registration process. The delegation event model is contrasted to an event filtration model where all events are delivered to target components regardless of whether they asked for them. Events (Cont’d)

Events: General Overview Recall our first consideration of events, where our first frame would not close, even when the end of main() was reached. We explained this behavior by thinking of our program as entering an “infinite loop” when the graphics are shown. This ‘infinite loop’ is actually an event-driven cycle, but we can think of it as a “while (true)” structure that periodically polls for user input.

The Real Story import java.awt.*; public class HelloGUI { public static void main (String[ ] arg) { System.out.println (“About to make GUI”); Frame f = new Frame (“Hello GUIs”); f.setSize( 200, 200 ); f.show(); System.out.println (“Finished making GUI”); }// main }// class HelloGUI We usually think of our program as a single, linear set of steps being executed. But something special happens when we create graphical objects.

import java.awt.*; public class HelloGUI { public static void main (String[ ] arg) { System.out.println (“About to make GUI”); Frame f = new Frame (“Hello GUIs”); f.setSize( 200, 200 ); f.show(); System.out.println (“Finished making GUI”); }// main }// class HelloGUI When Java sees that you’ve created a GUI, your program gets a second “set” of linear instructions. This is actually a separate “thread”, but don’t worry if that’s unclear for now. We can think of this as a second part of our program than handles special graphics-related tasks (such as drawing the window, etc.) The Real Story (Cont’d)

import java.awt.*; public class HelloGUI { public static void main (String[ ] arg) { System.out.println (“About to make GUI”); Frame f = new Frame (“Hello GUIs”); f.setSize( 200, 200 ); f.show(); System.out.println (“Finished making GUI”); }// main }// class HelloGUI This model is very important to understand because as it turns out, when an event occurs--such as mouse click, it happens in the “graphics side” of the model. Mouse Click occurs The code trapping this event appears in the graphics thread Actually, there’s a separate “event queue” that handles incoming events. But this is already complicated enough. Let’s just generalize and imagine that all events arrive in the ‘graphics side’ of things. The Real Story (Cont’d)

import java.awt.*; public class HelloGUI { public static void main (String[ ] arg) { System.out.println (“About to make GUI”); Frame f = new Frame (“Hello GUIs”); f.setSize( 200, 200 ); f.show(); System.out.println (“Finished making GUI”); }// main }// class HelloGUI Since the event arrived in the ‘graphics half’ of our program, we need a way to have it call a method in our program. This is known as a “call back”. callback Our event handling code The code trapping this event appears in the graphics thread The Real Story: “Call backs”

import java.awt.*; public class HelloGUI { public static void main (String[ ] arg) { System.out.println (“About to make GUI”); Frame f = new Frame (“Hello GUIs”); f.setSize( 200, 200 ); f.show(); System.out.println (“Finished making GUI”); }// main }// class HelloGUI callback So Java needs to call some event handling code that we write. The trouble is, how will Java know what we called out method? We can name them anything we want, and Java won’t necessarily know what methods handle events. But Wait! We can use interfaces, right? The Real Story: How?

Event Interfaces Java uses interfaces as its primary event handling scheme. If you implement an event-related interface, Java will know which methods to call. This is because the contract nature of interfaces requires all methods to appear in the implementing class. import java.awt.*; public class HelloGUI { public static void main (String[ ] arg) { System.out.println (“About to make GUI”); Frame f = new Frame (“Hello GUIs”); f.setSize( 200, 200 ); f.show(); System.out.println (“Finished making GUI”); }// main }// class HelloGUI callback public void actionPerformed (ActionEvent e) { // code doing something } This method MUST be there, so Java knows it can “callback” to it ActionListener

Why “Registration”? We are told that “event registration” must occur before event handling will occur. What does this mean? Well, since we can have any class handle events, we need to tell Java which object implements the proper event handling interface. This “registers” the component as being interested in receiving callbacks. import java.awt.*; public class HelloGUI { public static void main (String[ ] arg) { System.out.println (“About to make GUI”); Frame f = new Frame (“Hello GUIs”); f.setSize( 200, 200 ); f.show(); System.out.println (“Finished making GUI”); }// main }// class HelloGUI Where to callback?

An Example public class DemoFrame extends Frame { public DemoFrame( ) { super (“A poor use of inheritance, but simple”); Handler2 h = new Handler2(); this.setSize(400,400); this.setLayout(new FlowLayout()); Button b = new Button (“Click me”); this.add(b); this.show(); } // Constructor public static void main(String[] args) { DemoFrame df; df = new DemoFrame(); } // main } // DemoFrame

Another Example public class Handler2 implements ActionListener { public void actionPerformed(ActionEvent e) { System.out.println (“Button was clicked”); } } // Handler2 Why doesn’t this work?

public class DemoFrame extends JFrame { public DemoFrame( ) { super (“A poor use of inheritance, but simple”); Handler2 h = new Handler2(); this.setSize(400,400); this.setLayout(new FlowLayout()); JButton b = new JButton (“Click me”); b.addActionListener(h); add(b); show(); } // Constructor public static void main(String[] args) { DemoFrame df; df = new DemoFrame(); } // main } // DemoFrame Another Example (Cont’d)

Question??? We said we had to have a Listener to handle the event and it had to be an object. Does it have to be a separate object?

Another Example public class DemoFrame extends Frame implements ActionListener { public DemoFrame( ) { super (“A poor use of inheritance, but simple”); Handler2 h = new Handler2(); this.setSize(400,400); this.setLayout(new FlowLayout()); Button b = new Button (“Click me”); b.addActionListener(this); this.add(b); this.show(); } // Constructor public void actionPerformed(ActionEvent e) { System.out.println (“Button was clicked”); } public static void main(String[] args) { DemoFrame df; df = new DemoFrame(); } // main } // DemoFrame

Is There Any Other Event There? Anything can be an event. Including general protection faults. But for the most part, good programming dictates that handled events should come from the following area of input: Keyboard events Timing events Mouse events Other user action inputs a b c d

Java Event Handling Strategies With this basic understanding, we can investigate the FOUR primary means of event handling in Java Event Adapters Semantic Events Event Listeners Inheritance-based event handling Very similar Very general Very old We’ll not talk about this one…

ListenersStrategy No. 1 From the discussion about callbacks, we noted that interfaces were the primary mechanism for structuring our event handling. There are numerous event interfaces we can implement, roughly divided around categories of events. The next slide lists many of them. Don’t freak out because there are so many. We’ll highlight the most commonly used ones...

Most commonly used in this course Listeners: So Many Choices Package java.awt.event features: ActionListener MouseListener MouseMotionListener AdjustmentListener ComponentListener FocusListener ContainerListener ItemListener KeyListener WindowListener TextListener As it turns out, the ActionListener is part of the “semantic” event group, even though it’s an interface. So let’s focus on simple events like MouseListener...

MouseListener The MouseListener interface has several methods we have to code: public void mouseClicked(MouseEvent e) { } -- a timing-based determination; else the events are processed as pressed/releases public void mouseEntered(MouseEvent e) { } -- entry into component public void mouseExited(MouseEvent e) { } -- exit from component public void mousePressed(MouseEvent e) { } -- simply a press... public void mouseReleased(MouseEvent e){ } the corresponding release

import java.awt.*; import java.awt.event.*; public class MouseFrame implements MouseListener{ Color highlight, normal; boolean bHighlight = true; Frame fr; public MouseFrame () { fr = new Frame(“For demonstration only”); highlight = Color.red; normal = Color.gray; frame.setSize(400,400); Button b = new Button("Click"); b.addMouseListener(this); fr.setBackground(normal); fr.setLayout(new FlowLayout()); fr.add(b); fr.show(); } public static void main(String[] args) { new MouseFrame(); } To keep it simple, we ignore WindowEvents Note that when we run this the constructor will run and terminate MouseListener: An Example

public void mouseReleased(MouseEvent e){ System.out.println ("Changing color"); if (bHighlight) frame.setBackground(highlight); else frame.setBackground(normal); bHighlight = !bHighlight; } public void mouseClicked(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mousePressed(MouseEvent e) {} } // MouseFrame “click” MouseListener: An Example (Cont’d)

Event Listener Summary We need a class that implements the appropriate listener type. We need to “register” a component as interested in receiving events: XYZ addXYZListener ( ); Whatever listener we’re working with. E.g.: addMouseListener(this); addMouseMotionListener(myEventHandler);

There’s another strategy using “adapters”, using inheritance that could have saved us some trouble... The “WindowListener” interface required numerous methods. But only one was important to us. All the rest were coded as “no-op” or no operation methods Event Listener: Observations

Adapters public class MouseAdapter implements MouseListener { public void mouseClicked(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mousePressed(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} } Java has built-in classes called “event adapters” that implement each of the various event listeners. But all of these methods are “no-ops”. WHY???Strategy No. 2

Key to Adapters: Inheritance Why a bunch of no-op methods? Well, if you subclass the adapter, your class IS-A type of event listener. And you then only have to override the one or two methods you care about. The rest can be inherited as “no- ops” MouseFrame MouseAdapter

Parent class takes care of these import java.awt.*; import java.awt.event.*; extends MouseAdapter public class MouseFrame extends MouseAdapter implements MouseListener{ Color highlight, normal; boolean bHighlight = true; Frame frame; public MouseFrame () { frame = new Frame(“For demonstration only”); highlight = Color.red; normal = Color.gray; frame.setSize(400,400); Button b = new Button("Click"); b.addMouseListener(this); frame.setBackground(normal); frame.setLayout(new FlowLayout()); frame.add(b); frame.show(); } public void mouseClicked(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mousePressed(MouseEvent e) {} Event Adapters (Cont’d)

public void mouseReleased(MouseEvent e){ System.out.println ("Changing color"); if (bHighlight) frame.setBackground(highlight); else frame.setBackground(normal); bHighlight = !bHighlight; } public static void main(String[] args) { new MouseFrame(); } } // MouseFrame We override the one or two methods we care about Same behavior; less code; but we use up our single inheritance Event Adapters (Cont’d)

import java.awt.*; import java.awt.event.*; public class MouseFrame extends MouseAdapter implements MouseListener{ Color highlight, normal; boolean bHighlight = true; Frame frame; public MouseFrame () { frame = new Frame(“For demonstration only”); highlight = Color.red; normal = Color.gray; frame.setSize(400,400); Button b = new Button("Click"); b.addMouseListener(this); frame.setBackground(normal); frame.setLayout(new FlowLayout()); frame.add(b); frame.show(); } public void mouseReleased(MouseEvent e) { System.out.println ("Changing color"); if (bHighlight) frame.setBackground(highlight); else frame.setBackground(normal); bHighlight = !bHighlight; } public static void main(String[] args) { new MouseFrame(); } } // MouseFrame public class MouseAdapter implements MouseListener { public void mouseClicked(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mousePressed(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} } This comes with Java!

Big Picture Time So far, we’ve tinkered with different ways of coding very low-level event handling. But what if our event handling needs are very general. Consider this simple dialog box: cancel Are you sure you wish to proceed ? There’s not much interaction that needs to be supported. Mouse entry/exit might not be needed at all. ok

Event Listeners (interfaces) Event Adapters (inheritance) Costs Benefits Must code all methods; wasteful no-ops result Uses up single inheritance opportunity Keep all events in single class Good abstraction; override those methods you need Event Handling Options: How to Decide?

Debugging Event Handlers Debugging an event-driven program (whether applet or graphical application) is more tricky than debugging a non-event-driven program. With an event-driven Java program, you don't explicitly code any kind of event-handling loop that "polls" for occurring events, then calls the appropriate handler(s) for those events. Instead, the Java internals handle this polling action for you. Debugging becomes trickier because now you have to make sure that your event handling code works correctly. You also have to make sure you're handling the correct events in the first place! For example, your code for mouseEntered( ) may work perfectly, but if you're expecting it to get called when the user clicks a mouse button, it won't be!

So, in debugging event-driven programs written with Java, the steps are: Be sure you're handling the appropriate events: Map out on paper what events get thrown from what components, and what class(es) handle them. Handle the events appropriately: This is the kind of debugging you're already familiar with: Once you're sure the appropriate events are getting handled, the rest is being sure the event-handling code (and the code that the event handlers call) work. Debugging Event Handlers (Cont’d)

To compare the three event handling techniques, let’s see a *brief* example how all three might work on a common problem. Events: A Short Example My Program BUTTON TEXT AREA Panel subclass Goal: Create a simple Frame that holds a TextArea and Button. The Button toggles the ability to edit the TextArea The Panel holding the Button and TextArea is placed in a Frame subclass, which handles its own disposal

import java.awt.*; import java.awt.event.*; public class MyFrame extends Frame implements WindowListener{ public static final int iWidth = 300, iHeight = 500; public MyFrame() { this.setSize(iWidth, iHeight); this.addWindowListener(this); BorderLayout border = new BorderLayout(); this.setLayout(border); } public void windowClosing (WindowEvent e) { e.getWindow().setVisible(false); e.getWindow().dispose(); System.exit(0); } public void windowActivated(WindowEvent e) {} public void windowClosed(WindowEvent e) {} public void windowDeactivated(WindowEvent e) {} public void windowDeiconified(WindowEvent e) {} public void windowIconified(WindowEvent e) {} public void windowOpened(WindowEvent e) {} }// class MyFrame Constructor WindowListener Frames are not self-disposing! (Setting Frame invisible first eliminate flicker.) Events: A Short Example (Cont’d)

import java.awt.*; import java.awt.event.*; public class MyFrame extends Frame { public static final int iWidth = 300, iHeight = 500; public MyFrame() { this.setSize(iWidth, iHeight); this.addWindowListener (new WindowAdapter() { public void windowClosing (WindowEvent e) { e.getWindow().setVisible(false); e.getWindow().dispose(); System.exit(0); } }); BorderLayout border = new BorderLayout(); this.setLayout(border); } }// class MyFrame Advanced feature: “Anonymous Inner Class”: used as a short cut. For your code, use listeners Frames are not self-disposing! (Setting Frame invisible first eliminate flicker.) Events: A Short Example (Cont’d)

import java.awt.*; public class Driver { public static void main (String arg[]){ Notepad note = new Notepad(); MyFrame f = new MyFrame(); f.add(note, BorderLayout.CENTER); f.show(); }//main }//class Driver Events: A Short Example (Cont’d)