Callbacks. Callbacks Copyright 2007 by Ken Slonneger 1



Similar documents
Homework/Program #5 Solutions

// Correntista. //Conta Corrente. package Banco; public class Correntista { String nome, sobrenome; int cpf;

INTRODUCTION TO COMPUTER PROGRAMMING. Richard Pierse. Class 7: Object-Oriented Programming. Introduction

CS 335 Lecture 06 Java Programming GUI and Swing

Programming with Java GUI components

5.17 GUI. Xiaoyi Jiang Informatik I Grundlagen der Programmierung

Using A Frame for Output

Extending Desktop Applications to the Web

public class Craps extends JFrame implements ActionListener { final int WON = 0,LOST =1, CONTINUE = 2;

Lab 1A. Create a simple Java application using JBuilder. Part 1: make the simplest Java application Hello World 1. Start Jbuilder. 2.

The Basic Java Applet and JApplet

Remote Method Invocation

Graphical User Interfaces

GUIs with Swing. Principles of Software Construction: Objects, Design, and Concurrency. Jonathan Aldrich and Charlie Garrod Fall 2012

Advanced Network Programming Lab using Java. Angelos Stavrou

file://c:\dokumente und Einstellungen\Marco Favorito\Desktop\ScanCmds.html

GUI Event-Driven Programming

Assignment No.3. /*-- Program for addition of two numbers using C++ --*/

Nexawebホワイトペーパー. Developing with Nexaweb ~ Nexaweb to Improve Development Productivity and Maintainability

The Abstract Windowing Toolkit. Java Foundation Classes. Swing. In April 1997, JavaSoft announced the Java Foundation Classes (JFC).

CSS 543 Program 3: Online Tic-Tac-Toe Game Professor: Munehiro Fukuda Due date: see the syllabus

Tutorial Reference Manual. Java WireFusion 4.1

Analysis Of Source Lines Of Code(SLOC) Metric

JiST Graphical User Interface Event Viewer. Mark Fong

Using the Monitoring and Report Viewer Web Services

Java GUI Programming. Building the GUI for the Microsoft Windows Calculator Lecture 2. Des Traynor 2005

An Overview of Java. overview-1

D06 PROGRAMMING with JAVA

Fondamenti di Java. Introduzione alla costruzione di GUI (graphic user interface)

Essentials of the Java(TM) Programming Language, Part 1

How To Build A Swing Program In Java.Java.Netbeans.Netcode.Com (For Windows) (For Linux) (Java) (Javax) (Windows) (Powerpoint) (Netbeans) (Sun) (

J a v a Quiz (Unit 3, Test 0 Practice)

Model-View-Controller (MVC) Design Pattern

Supplement IV.C: Tutorial for Oracle. For Introduction to Java Programming By Y. Daniel Liang

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

How to Install Java onto your system

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Swing. A Quick Tutorial on Programming Swing Applications

Chapter 2 Introduction to Java programming

CS170 Lab 11 Abstract Data Types & Objects

How To Write A Program For The Web In Java (Java)

You are to simulate the process by making a record of the balls chosen, in the sequence in which they are chosen. Typical output for a run would be:

CS108, Stanford Handout #33. Sockets

Introduction to Object-Oriented Programming

More on Objects and Classes

Hello World RESTful web service tutorial

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

Creating a Java application using Perfect Developer and the Java Develo...

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Lösningsförslag till tentamen

Java Interview Questions and Answers

Contents. 9-1 Copyright (c) N. Afshartous

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius

LAB4 Making Classes and Objects

CS506 Web Design and Development Solved Online Quiz No. 01

Assignment # 2: Design Patterns and GUIs

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Syllabus for CS 134 Java Programming

Overview of Web Services API

Classes and Objects. Agenda. Quiz 7/1/2008. The Background of the Object-Oriented Approach. Class. Object. Package and import

11. Applets, normal window applications, packaging and sharing your work

How Scala Improved Our Java

Essentials of the Java Programming Language

JAVA Program For Processing SMS Messages

DHBW Karlsruhe, Vorlesung Programmieren, Remote Musterlösungen

How to create/avoid memory leak in Java and.net? Venkat Subramaniam

Introduction to Programming

System.out.println("\nEnter Product Number 1-5 (0 to stop and view summary) :

Construction of classes with classes

WA2099 Introduction to Java using RAD 8.0 EVALUATION ONLY. Student Labs. Web Age Solutions Inc.

GOPAL RAMALINGAM MEMORIAL ENGINEERING COLLEGE. Rajeshwari nagar, Panapakkam, Near Padappai, Chennai

Introduction to Java

CS211 Spring 2005 Final Exam May 17, Solutions. Instructions

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013


Word Count Code using MR2 Classes and API

Basics of Java Programming Input and the Scanner class

How to Convert an Application into an Applet.

Building Java Programs

JAVA - MULTITHREADING

CS193j, Stanford Handout #10 OOP 3

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

Third AP Edition. Object-Oriented Programming and Data Structures. Maria Litvin. Gary Litvin. Phillips Academy, Andover, Massachusetts

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

Object-Oriented Programming in Java

Dev Articles 05/25/07 11:07:33

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Intruduction to Groovy & Grails programming languages beyond Java

Collections in Java. Arrays. Iterators. Collections (also called containers) Has special language support. Iterator (i) Collection (i) Set (i),

public class demo1swing extends JFrame implements ActionListener{

Introduction to the Java Programming Language

LINKED DATA STRUCTURES

Java Cheatsheet. Tim Coppieters Laure Philips Elisa Gonzalez Boix

LAB 1. Familiarization of Rational Rose Environment And UML for small Java Application Development

Transcription:

Callbacks Callbacks refer to a mechanism in which a library or utility class provides a service to clients that are unknown to it when it is defined. Suppose, for example, that a server class creates a window and recognizes events in that window. Suppose, in addition, that various clients need to be informed of these events so that they can perform actions of their own. When such an event occurs, the server class needs to invoke methods in one or more of the clients associated with the server, but the server has no prior knowledge of which clients will be attached and the names of the methods that need to be called. In C and C++, this situation is handled by having the clients register with the server by sending it function pointers that refer to the methods that need to be executed when an event occurs. These functions are called callback functions. When an appropriate event happens, the server calls the methods in the appropriate clients by invoking the formal parameters that denote the function pointers that were register by the clients. But Java has no user-defined function pointers. Java provides the callback mechanism with interfaces using the following steps: 1. An interface is defined with an abstract method whose name is known to the server. Callbacks Copyright 2007 by Ken Slonneger 1

2. Each client that has actions to be performed when a server event occurs implements the interface, thereby giving code for the abstract method. 3. When a client registers with the server, the server holds an instance variable that refers to the client and whose type is the interface type. 4. The server class invokes the client action by calling the interface method for that client. Example We define a server that creates a window with four buttons. The server maintains a list that can hold references to any number of clients. When any of the first three buttons is clicked, an action in one of the first three clients will be performed. When the fourth button is pressed, the actions in all of the clients will be executed. The connection between the server and the clients is provided by an interface called Callback. interface Callback void performcallback(string str); The entire program is controlled by a class that creates the server and three clients. 2 Copyright 2007 by Ken Slonneger Callbacks

import java.util.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Callbacks public static void main(string [] args) WindowServer ws = new WindowServer(); ws.setsize(300,200); ws.setvisible(true); ClientOne client1 = new ClientOne(ws); ClientTwo client2 = new ClientTwo(ws); ClientThree client3 = new ClientThree(ws); Note that the clients are made aware of the server by passing a reference to the server to their constructors. The server class WindowServer contains: An instance variable of type List that contains references to the clients that register. A constructor that creates the window with the four buttons. An inner class ButtonHandler for handling the button clicks. A method for registering clients, adding them to the List. Callbacks Copyright 2007 by Ken Slonneger 3

A method for unregistering clients, deleting them from the List. Note that all references to clients are as instances of the interface Callback. class WindowServer extends JFrame private java.util.list clientobjs = new ArrayList(); private JButton button1, button2, button3, button123; WindowServer() super("callback Window"); setdefaultcloseoperation(jframe.exit_on_close); Container cp = getcontentpane(); cp.setlayout(new FlowLayout()); button1 = new JButton("Button 1"); button1.addactionlistener(new ButtonHandler(1)); button2 = new JButton("Button 2"); button2.addactionlistener(new ButtonHandler(2)); button3 = new JButton("Button 3"); button3.addactionlistener(new ButtonHandler(3)); button123 = new JButton("Button 123"); button123.addactionlistener(new ButtonHandler(123)); cp.add(button1); cp.add(button2); cp.add(button3); cp.add(button123); 4 Copyright 2007 by Ken Slonneger Callbacks

class ButtonHandler implements ActionListener private int value; ButtonHandler(int n) value = n; public void actionperformed(actionevent evt) if (value>100) System.out.println("Button 123 pressed."); notifyclients("button 123"); else System.out.println("Button " + value + " pressed."); ((Callback)clientObjs.get(value-1)). performcallback("says Hello"); void registercallback(callback client) clientobjs.add(client); Callbacks Copyright 2007 by Ken Slonneger 5

void unregistercallback(callback client) clientobjs.remove(client); void notifyclients(string str) for (Iterator it = clientobjs.iterator(); it.hasnext(); ) ((Callback)(it.next())).performCallback(str); Observe that Objects in the List need to be cast into Callback objects before the interface method performcallback can be called. Window Server 6 Copyright 2007 by Ken Slonneger Callbacks

One client is defined below. The other two clients can be defined in an analogous manner. class ClientOne implements Callback private WindowServer server; ClientOne(WindowServer ws) System.out.println("Creating Client One"); server = ws; server.registercallback(this); public void performcallback(string str) System.out.println("Client One " + str); Callbacks Copyright 2007 by Ken Slonneger 7

Sample Output Creating Client One Creating Client Two Creating Client Three Button 1 pressed. Client One says Hello Button 2 pressed. Client Two says Hello Button 3 pressed. Client Three says Hello Button 123 pressed. Client One Button 123 Client Two Button 123 Client Three Button 123 Note: The event handling mechanism in Java works in a similar manner. Objects that implement "listener" interfaces are registered with the objects that generate events (buttons, text fields, and so on) so that they can be notified when the particular events occur. 8 Copyright 2007 by Ken Slonneger Callbacks