Document not found! Please try again

A Java package for Novice Interactive and Graphics Programming

4 downloads 10384 Views 488KB Size Report
Graphics Programming. Ursula Wolz. Department of Computer Science. The College of New Jersey, Box 7718. Ewing, New Jersey, 08628-0718, USA. +Ol 609 ...
simplelo:

A Java package for Novice Interactive Graphics Programming Elliot Koff man

Ursula Wolz Department

Department of Computer Science The College of New Jersey, Box 7718 Ewing, New Jersey, 08628-0718, USA +Ol 609 771 2268

ABSTRACT

continue until it is their turn to do so. This model is easy for novices to understand and also reinforces the idea that an algorithm is a sequence of steps that describes a solution.

This paper describes how to incorporate user interactivity and graphics into a first course in computer science. Problems and alternative solutions are discussed. A Java package called simple10 that we developed is presented. It allows novice programmers to build simple GUI -based programs while maintaining good design principles. The package includes methods for requesting data from the user including integers, reals, string and Booleans. It also supports simple menus, graphics displays and text file handling.

Modem GUI environments support a different interaction. Both the user and the system may be engaged in a number of simultaneous activities through display windows that either may modify. Rather than responding to a simple prompt or a hierarchical menu, the user initiates activities through a variety of devices such as buttons, menus, dialog boxes, or more directly through mouse movements and clicks as well as key strokes. The program therefore must be attuned to a variety of input devices; ready to change context at any time. Clearly, this is not a methodical turn-taking dialog that can be captured in a straightforward sequential process. Programming GUIs therefore requires some level of comprehension of input events (such as mouse clicks) and concurrency (to switch contexts based on user input).

Keywords interactivity,

Java,

of Computer and Information Science Temple University Philadelphia, PA 19122, USA +Ol 215 204 1913

[email protected]

wolz @tcnj.edu

CSl, graphics, interface

and

programming,

user

1. INTRODUCTION Twenty years ago simple constructs in BASIC and Pascal made interactivity and graphics accessible to novice programmers. The requisite techniques were easily incorporated into introductory curricula in Computer Science[3]. Students were highly motivated to complete programming assignments because projects were fun. Current introductory CS courses have lost that motivation because graphics and interactive programming is difficult in modern Graphical User Interface (GUI) environments. Programming GUIs is inherently concurrent and depends upon mastery of concepts such as events and threads[2,7]. In this paper we discuss some possible solutions to this problem, and present a support library called simpleI that we developed[4]. The package allows novice programmers immediate access to GUI functionality and text file handling in Java.

GUI programming is also inherently object-oriented[6]. Managing the sheer complexity of multiple windows and input devices requires a programming viewpoint that encapsulates data and methods and goes beyond either procedural or functional models. At least two questions arise with regard to a first course in programming. To what degree should students be required to master the nuances of GUI concepts? To what degree should they be required to master object-oriented techniques? Pessimistically, programming GUIs is hard, and should therefore be avoided. But then we loose the compelling interactive and graphics projects[ 1,8]. Optimistically, programming GUIs reinforces object-oriented programming. Besides, as our students contend, it is fun.

The “old fashioned” languages such as Turbo Pascal included graphics and interactive primitives that directly controlled the input and output devices of these machines. To receive user input, a programmer wrote code that suspended all activity until the user response was complete. This is a form of a turn taking dialog. Neither the computer nor the user may

We have identified five general approaches to the problem:

PermissIon to make digital or hard copies of all or part of this work for personal or classroom use is granted without fee provided that copies are not made or distributed for proflt or commercial advantage and that copies bear this notice and the full c~tatton on the first page. To copy otherwise, to republish, to post on servers or to redistribute to IIS~S. reqwes pnor specific permission and1or.a fee. ITiCSE ‘99 6/99 0x0~. Poland 0 1999 ACM l-58113.087.Z/99/0005.,.$5.00

139

1.

Ignore GUIs entirely. Require students to write programs with input/output constructs from libraries such as C++ ioStream, C stdio, and Java classes System.in and out.

2.

Promote non-sequential programming models from the onset by embracing GUI and concurrent programming; for example introduce the Java Abstract Windows Toolkit (AWT)[2] and the Java Thread class immediately.

3.

Have students write complete programs.

4.

Include instruction in the use of GUI-design tools such as Visual Basic.

5.

Use special purpose libraries.

program

fragments

rather

than

We haveadopted the fifth solution in the belief that students should learn to write complete programs early on [5], that they have enough to master without the complexity of nonsequential models, and that learning GUI-design environments detracts from the proper focus of a first semester course in Computer Science. Furthermore, as we*will argue in the next section, we believe that ignoring GUIs is not only boring, but actually thwarts the development of good design and implementation skills, especially in Java.

appreciation for interactivity issues as well as for delegating responsibility to other classes. Students are quickly engaged in object-oriented design, if only on a superficial level.

2.1

The simple10 package we describe allows novice students to write a single sequential Java program that follows a turntaking dialog within the broader context of a GUI and threadbased Java environment. The student writes a complete application in Java, inheriting interactive functionality from our class SimpleGUt. As we will show, our model reinforces good object-oriented programming style in Java without initially burdening the student with many complex concepts and a deluge of esoteric detail. Furthermore, unlike GUI-based design tools that may detract from the focus of the course, our package reinforces essential programming principles such as using methods (procedures), passing parameters, and operating on the results of functions.

2. EXAMPLE

WITH

simple10

3. THE simple10

1: A Temperature

1. 2. 3. 4. 5. 6. 7. 8.

3.1

The interface is for classrobm use. Beginners need to focus on a single thread. Keep a history of results. Keep it simple. Save and print results. Cover the basic data types plus menus. Integrate graphics and interactivity. Support simple access to text files for the basic primitive types plus Strings.

The SimpleGUI

environment

In Figure 2, a main window, labeled “User Interaction History” appears when a SimpleGUI object is created. All input methods (with prefix “get”) display their prompt and their result in this window. There are two output methods: displayResult, shown above, and displayRow, that displays the contents of an array. The history window is useful for instructional purposes: the entire execution may be viewed, saved or printed, for example for inclusion in a student lab report. The attributes of the history window may be customized, for example the font size may be increased during a lecture for viewing by a large audience.

}

9;}

Conversion

PACKAGE

Our goals for the design of the simple10 package were:

// File: ConvertTemp.java public class ConvertTemp extends SimDleGUI ( private double fahrenheit; public void getFahrenheit ( fahrenheit = aetDouble("Temperature in fahrenheit");)

Figure

Good Design

Figure 2 showed an error in the user interaction. The student gains an appreciation for the need to create robust code without being required to master complex concepts. The student can focus on getting the requisite input, without distracting problems that are not central to the task at hand.

// File: ConvetApp.java import simp:LeIO.*; public class ConvertApp ( public static void main(String args[] ) { ConvertTemp ct = new ConvertTempO; ct.getFahrenheit(); ct.showCelsius 0; } ) // Class ConvertApp

private double FahrToC() ( return .'I* (fahrenheit - 32)/ // Class ConvertTemp

Promotes

When students initially use standard text-based packages such as Java’s System.out.println, or C’s stdio, either their interactive code is terribly brittle, or they get side-tracked from the algorithm they are implementing as they grapple with converting text to other data types. Typically, the student must convert from bytes or the String class to the proper numerical type. simple10 promotes the concept of delegating responsibility to predefined classes. The code the student writes is a straightforward example of a method call and error detection is built into SimpleGUI methods.

Figure 1 shows an example of a first program written by a student at TCNJ to convert temperature from Fahrenheit to Celsius. Two classes are defined, an application class ConvertApp and a support class ConvertTemp. The application creates an instance of ConvertApp and calls its methods getFahrenheit and showcelsius. Since ConvertTemp extends the class SimpleGUI, it can call SimpleGUI methods such as getDouble and displayResult (underlined in the code.).

public void showCelsius ( dis~lavRer~("In Celsius: "+FahrToC());

simple10

One aspect of good design is to maintain the integrity of the language in the support package. Therefore, the simple10 package encourages the use of class instances rather than static classes and discourages the use of class (static) variables except where they are appropriate. This is in contrast to packages that enhance the usability of System.in and System.out, which may encourage students to misuse static objects. Another aspect of design is to concentrate on the task at hand, and delegate responsibility for sub-tasks to other classes or methods. This is classic top-down design.

Program

Figure 2 shows a sample run. All of the user interaction, including the error dialog, is handled by the simple10 package. The novice programmer is not distracted from the problem at hand: temperature conversion, but gains an

3.2

Text

responses

In Figure 1 real input is received from the user via the getDouble method. The SimpleGUI class also supports

140

Figure

2: Sample

Execution

of Temperature

Conversion

Program

methods for primitive types int, and char as well as the String class. We chose to support only one primitive type each for reals and integers to reduce complexity. All of the getType methods allow the programmer to specify the display prompt. The methods for the primitive types also allow the programmer to specify a lower and upper bound, for example, a range of integers. The getType methods are overloaded. A single string argument to the method resorts to a default range. The student can also specify the range as the second and third arguments. This is an example of how we reinforce standard Java techniques. Novice programmers see many examples of method overloading before they write it themselves.

3.3

Programming

Boolean

boolean work = getBoolean(“Are

we having fun?“);

boolean work = getBoolean(“Are

we working”,

Choices

Novice programmers may not appreciate the full potential of Boolean values because they have little opportunity to receive such values from a user. In traditional text-based dialog, the user might respond to a true/false (yes/no) query with a character such as “Y.” The student is forced off the task at hand to the problem of what character input to tolerate, and how to interpret the result. The student often must encode a complicated statement such as “if the user typed one of the following characters then do this, otherwise do that.”

Figure

3.4

The overload method getBoolean encourages student to use boolean types, Fig. 3 shows the display and corresponding code. The first form returns true when checked. Specification of a choice is allowed when three strings are given, returning true corresponding to the second one.

Multiple

3:

Examples

Choice

of

“yes”, “no”);

getBoolean

Responses

Another problem in text-based dialog is selecting from a discrete set of input, for example selecting from the days of the week. Such user input can control cascading if/then/else or switch statements. However, implementing the input choice is

141

often far more complicated than implementing the decisionchoice, and the former detracts from the latter. For example, the student may have to write code that requests a number corresponding to the day, then confirm that the number is in bounds etc. A classic repetitive solution for such error detection is fundamentally wrong with GUIs in Java. A thread should be used instead. More to the point, the user input should come from a menu not from an integer value.

class rather than storing to a file. However, the serializing features of Java are still relatively new and unstable[2]. File and stream handling in Java is very sophisticated, and consequently very complicated for novices. We therefore extended the Java Reader and Writer classes, creating SimpleReader and SimpleWriter in the simple10 package. These classes support the classic open file, operate sequentially, close file model. They have methods (getType and putData) that correspond to SimpleGUI getType and displayResult methods. Our basic data types can be stored as strings in a text file. We use these classes and methods sparingly, and defer discussion of serialized objects until CS2.

Figure 4 shows how we support menus with SimpleGUI method calls. The format follows the style of the AWT for adding items to a GUI component, and thus lays the foundation for understanding the AWT later. The programmer creates the menu with SimpleGUI method createMenu, then calls addchoice repeatedly with a string argument. The method getchoice uses its string argument as the prompt for the menu, and returns an integer corresponding to the list position of the selected item.

4. SUMMARY The simple10 package gives students easy access to interactivity with graphics in Java. But the package was intentionally designed to be limited. We encourage students to go beyond it and learn to use the AWT. The design of the package was modeled on the AWT. It encourages students to create, instantiate and extend classes, thus supporting good object-oriented programming habits in Java. The simple10 package is implemented in Java 1.1. The Java 1.2 enhancements should not have an impact. It has been tested on MacOS( 7.5 and up) under Codewarrior, on Windows95 under JBUILDER and Semantic Cafe, and on Solaris(Sun) with the JDK. It can be found on the web at ftp://ftp.tcnj.edu/pub/tcnj/wolz/psjava.

public int workDay ( createMemO; addChoice("Monday"); addChoice("Tuesday"); addChoice("Wednesday"); addChoice("Thursday"); addChoice("Friday"); return getChoice( "Which will be a vacation day?"); ) Figure

3.5

Graphics

4: An

example

5. ACKNOWLEDGEMENTS Lana Kucherovsky implemented version 1. Versions 2 and 3 were developed by TCNJ undergraduates. Thanks to Joe Turner, Penny Anderson, Norm Neff and Shawn Sivy for advice on pedagogy and system design.

of getMenu

6. REFERENCES

and Interactivity

Rudimentary graphics programming is compelling for beginners, and has pedagogical value because the function calls that render graphics images give practice in passing arguments. The Java AWT class Graphics supports the standard objects: lines, rectangles, ovals, arcs as well as strings. These may be displayed in a multitude of colors and figures may be filled. Images such as gifs and jpegs may also be displayed.

[II Brown, C., et. al. Introductory Computer Science, Proceedings of ACM Computer Science Conference, Indianapolis, IN, February 1993.

PI Chan P. and R. Lee The Java Class Libraries [31 Koffman, E. ,Turbo Pascal Sh Edition, Reading MA. 1995.

A Graphics ob.ject is instantiated when an AWT component such as an Applet is created. The corresponding Graphics instance is called within the component’s paint method. To render graphics, the programmer extends the Applet, and overrides the paint method to include method calls to the Graphics instance. Students grasp the technique because it reinforces concepts of extending a class and over-riding a method.

Addison Wesley,

[41 Koffman E. and U. Wolz, Problem Solving Addison Wesley, Reading MA. 1999.

with Java,

151 Koffman E. and U. Wolz,

CSl Using Java Language Features Gently, in Proceedings of ITiCSE ‘99, Integrating Technology into Computer Science Education, ACM, Crakow, Poland, 1999.

Without a thorough knowledge of events, even experts find it hard to integrate graphics and interactivity. simple10 contains a class SimpleGraphic. Just like an Applet is part of a web browser, the SimpleGraphic object is part of a SimpleGUI object. Students draw with the same technique as with an Applet, but can also use SimpleGUI interactive methods.

3.6

Second

Edition, Addison Wesley, Reading MA. 1998.

if51 Shneiderman,

B. Designing The User Interface, Edition, Addison Wesley, Reading MA. 1997.

[71 van der Linden, P. Just Java, Second Edition, Press, Mountain View, CA, 1997.

PI Wolz,

Third SunSoft

U., D. Domen, & M. McAuliffe, Multi-media integrated into CS 2: An interactive children’s story as a unifying class project , SIGCSE Bulletin Vol. 29, no. 3, 1997, Conference Proceedings of ITiCSE 1997.

Files

Text files are typically part of the CS 1 curriculum, however in Java, persistent storage of data should be done by serializing a

142