A Simple Java Package for GUl-like Interactivity - Semantic Scholar

12 downloads 16861 Views 620KB Size Report
this package is that it is easy to implement using the Swing class. Therefore, it can ... David Arnow (Brooklyn College of City University of New. York) makes the ...
A Simple Java Package for GUl-like Interactivity Ursula Wolz Department of Computer Science The College of New Jersey, Box 7718 Ewing, New Jersey, 08628-0718 [email protected]

Elliot Koffman Computer and Information Science Department Temple University Philadelphia, PA 19122 koffman @cis.tem ple.ed u

fairly evenly between those who advocated their use and those who were against their use. The following comment by H. Conrad Cunningham (University of Mississippi) succinctly summarizes the two points of view:

Abstract This paper discusses the motivation for a simple package designed to incorporate user interactivity into a first course in computer science. The package enables novice programmers to build programs with GUI-like interactivity while maintaining good design principles. An advantage of this package is that it is easy to implement using the Swing class. Therefore, it can be used as a case study to illustrate Java features. 1 Background and Motivation Many Java textbooks for CS 1 utilize simple packages for Java input/output. Some classes that were developed to simplify console input/output are: ConsoleReader [3], Text [2], SimpleInput [1], and Savatchln [5]. These classes were written because the textbook authors and teachers of CS 1 recognized that console-based input/output in Java is difficult for novices to use. At the same time, a few packages were also written that permitted GUI-like interactivity. Examples of these packages and classes are: simpleIO [4], javaBook [9], and JPT [6]. These packages were developed because their implementers recognized that console-based input/output was tedious and uninteresting to students who were accustomed to applications with Graphical User Interfaces (GUIs). The package developers also felt that novice students should be able to write programs with GUI-like interactivity before mastering the Java APIs that would enable them to build their own GUIs: AWT and Swing.

"On one hand, use of simplified I/O or GUI packages can make Java easier to teach and use in CS1/CS2. So the various packages that are available with various textbooks can be helpful. And we want to convey to our students that it is easy to add on significant capabilities to Java and other such languages. On the other hand, there is concern that use of a nonstandard, add-on package might be confusing to first year students. Students tend to take what they learn as being part of Java. When they move to another environment, they are somewhat lost and confused. They have the overhead of relearning an I/O package or installing the one they are accustomed to. There is thus some sentiment to only teaching the "standard" (whatever that means with Java)." A. Joseph Turner (Clemson University), makes the following point in favor of using packages: "I haven't tried teaching CS1 or CS2 using only the classes in the standard Java library, but unless you want to limit yourself to reading only a character at a time or a line at a time (as a string), you don't want to use only the I/O facilities in standard Java. (There are some ways to do a bit better than reading only characters or lines, but the overhead and complexity of doing so are out of the question for beginning students as far as I am concerned.)"

In early April, 1999 there was a thread on the SIGCSE listserve which discussed the use of non-standard packages for teaching CS 1 in Java. The messages seemed to be split

David Arnow (Brooklyn College of City University of New York) makes the following argument against the use of packages:

Permission to make digital or hard copies o1 all or part of this work for personal or classroom use is granted without fee provided that copies are not made or distriblJted for profit or commercial advantage and that copies bear this notice and the full citation on the first page. To copy otherwise, to republish, to post on servers or to redistribute to lists, requires prior specific permissmn and/or a fee.

"There is another argument in favor of NOT providing a special I/O package for student use in CSl/Java. While constructions such as

SIGCSE 2001 2/01 Charlotte, NC, USA © 2001 A C M ISBN 1 - 5 8 1 1 3 - 3 2 9 - 4 / 0 1 / 0 0 0 2 . . . $ 5 . 0 0

Buffere¢lReader

br

=

new BufferedReader( new

InputStreamReader

new

FilelnputStre~un

new

11

File("m~input"

( (

) )) )

may be introduced as "boilerplate", they also provide an opportunity to:

along in the course (which it ought to at some stage), then an I/O or Graph package is an ideal candidate."



emphasize the idea of classes as models, repositories of particular sets of behavior.



illustrate the use of composition



foster the notion and UTILITY of abstraction

What have we learned from this thread? There are rather strong opinions about the pros and cons of using packages. If authors or teachers wish to use a package, they should think of the package as "training wheels" to give a student the feel for programming with GUIs in Java without the overhead of learning the AWT from the start. The package should be fairly easy to implement, so that students have no difficulty understanding it as a case study.

as

In connection with the latter, students, even CS1 students, can appreciate the fact (and the accompanying discussion) that the last two lines of the above code can be replaced with

2 A Simple Package for User Interaetivity With this background in mind we developed a new package as a replacement for an earlier, more powerful one [8] that was not easy to implement and understand because it was designed using Java AWT and not Swing. In addition to displaying dialog windows and menus for input, the earlier package provided methods for incorporating user interactivity in graphics programming and for simplifying file input/output. It also provided a history of all user interaction with objects that inherited class SimpleGUI (part of the package).

S~s~mn. :tn or new

UR.T.,( " h t t p

: //~v~v~. a ~ s t . o r g " ) . o p e n , S t : r e a m ( ) ) )

or

all sorts of other things eventually because each of these things play the "role" of an InputStream. In other words, if one's goal is to take an object-oriented approach in CS1 Java's I/O classes can be viewed as an asset, not a liability. (As a side note, this i/o stuff usually turns out to be the LEAST of the students' problems in CS1.)"

The new package is more modest in its goals. It enables novice programmers to easily display dialog windows for input, including menus. It also enables the user to display message windows for "one-line" output or to append output to an output text area for more extended output. The new package consists of a single class named IO. It uses four methods defined in the JOptionPane class of the Swing API [7].

Michael G. Branton (Stetson University) advocates teaching basics of the AWT first instead of using packages: "You can also do it with Java without that much fuss. I've taught the course 3 times now using AWT. you don't need very much of it to put a text field or 2 and a button on the screen, folks. There seems to me a lot of hand-wringing over this, but I've found that my students donut find this difficult to deal with at all. It's the algorithm development that's still the "hard part." My experience is that teaching them enough of the GUI for CS1 doesn't take much time at all. I still have plenty of room for the topics I consider important, and text fields and buttons give them something very concrete (in a virtual sort of way :-) ) to think of as objects right off the bat."

2.1 InputMethods The input methods in class IO are static methods named getInt0, getBoolean0, getDouble0, getChar0, and getString0. These methods take a single String argument a prompt. Each method displays a dialog window that accepts a data value of the indicated type. If the user enters incorrect data, an error window is displayed and the dialog window is displayed again. The method call I O . g e t S t r i n g ( " w h a t is your name?") displays the dialog window below with the title "input". The prompt string appears as a label in the dialog window.

Finally, Judy Bishop (University of Pretoria) makes the following points in favor of non-standard packages: "1. Java is an extensible language, with extensions coming via packages (APIs). In today's world, the ability to harness this power is more integral and more important for fresh minds to understand in *week one*, than a long-winded object instantiation, four brackets deep.

"-' !:~'~ii I i~i!,,i

2. An I/O class is an excellent case study in its own right as it illustrates exception handling, as well as tokenizers and string functions. It also does not have to be long: our Text class is 2.5 book pages of code, providing 10 methods for input, output and file opening.

~ i ~ ~ i ~ :~~ i ~

~

~

~i ~%i., ...-~"%i~

1

The method body consists of a call to method showlnputDialog0 of the JOptionPane class. We included

3. If a lecturer feels very strongly about teaching Java at the rock face, and is not convinced by point 1, then I would still suggest that when Writing Your Own Package! comes

12

this method for completeness, although it would be easy for a student to call method showlnputDialog0 directly.

The method call

public static String getStrlng(Strlng prompt) return JOptlonPane.showInputDialog(pro~t)l

verifies that the integer entered is within the range indicated by its second and third arguments (optional). If the integer is within range, it is returned as the method result. Otherwise an "out of range" error message window pops up.

IO.getInt("Enter

(

}

The method call zo. getChar ( "Enter a l e t t e r " ) displays a dialog window asking for a letter. If the user types in a single character ( s t r . l e n ~ h ( ) == 1 ) , that character is returned as the method result. If the user types in more than one character, an error window like the one below is displayed.

•-~!~

!

!ii~iii!i¸

!

!!

~

!i~¸ i ~

a number

between

1 and

10",i,10)

i ¸ ~i!

After the user presses OK, the original dialog window reappears. This version of method getlnt0 follows. public

static

String

After the user presses OK, the original dialog window is displayed again and the single character typed in is returned as the method result.

int

getZnt(String pz~, tnt man, int

hum JOptionPane. showInputDialog

try {

max)

{

(prompt) i

int intNum = Znteger.parseZnt (hum) i f ( l n t N u m >= m i n a& i n t N u m ~ - m ~ )

(

return intNumt } else ( J O p t i o n P a n e , s h o w M a s s a g e D i a l o g (n u l i, i n t N u m + " is o u t o f r a n g e " + rain + " t o " + m a x + " - try again", "Error", JOpt ionPane. ERROR_MXSBAGI }I return getlnt(pr~t, min, maR) ;

A recursive version of method getChar0 follows. You can discuss this method when you introduce recursion. public stati= char getChar(String pro~pt) ( String str= JOptionPane.showlnputDialog(prm~t); if ( s i r . l e n g t h ( ) = = I) ( return str.charAt(0); } else ( JOptlonPane.showMessageDialog(null, str+ " is n o t a s i n g l e c h a r a c t e r - t r y a g a i n " , "Error", JOptlonPano.ERROR_MES~AGE); return getChar(prom~t);

) } catch (NumberFormat~eption e) { J O p t i o n P a n e . s h o w M e s s a g e D i a l o g (null, "Invalid integer " + hum + " - t r y a g a i n " , "Error:", JOpt ionPane. ERROR_MESSAGE ); r e t u r n getInt(pro~spt, m i n , m a x ) ;

)

)

)

}

Y o u can discuss this method when you introduce if-else

and try-catch statements and exceptions.

Methods getlnt0 and getDouble0 catch exceptions due to invalid numeric input and display an error window if an exception occurs.

Method getBoolean0 displays a window with two buttons. The method call ZO. g e t B o o l e a n ( " A r e y o u h a p p y ? " )

displays the dialog window below with the default labels of "yes" (for true) and "no" (for false). ~~i?'i ~1%~i?"~:~'~i~i"i ' ~ " '~'~~~'~"~i ~?'~T~i~'~~'~'~'~'~'~!~7 '~!?~7.......... /i~i~ ! ~! :~i~!!i~'' !'~ ~ i i i ~'~'i

After the user presses OK, the original dialog window reappears.

13

The user can also provide his/her own button labels corresponding to true and false by adding two optional arguments. The method call

Method getChoice0 follows. The method returns the subscript in array coffeChoices corresponding to the button that is pressed.

IO. g e t B o o l e a n { "What is ~ o u ~ state? ", "happ1,", "sad") publlc

static

causes the following dialog window to appear. int

n

-

Int g e t C h o i c e ( S t r i n E q u e r y , String[] options)

{

JOptionPane.showOptionDialog(null,

q u e z y , " M u l t i p l e a h o i c e question", JOptionPane.YESNO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, optlon8[0])7 r e t u r n nl

}

2.2 Output Methods Now we turn our attention to output methods. Method displayResult0 has a String argument and displays that string in a message dialog window: public {

Both versions of method getBoolean0 follow. Both methods return true if the user selects the first button (n -o). The second version uses array options (an array of obSeces) to store the strings corresponding to true and false. You can use these two versions to illustrate method overloading and polymorphism. p u b l i c static b o o l e a n g e t B o o l e a n ( S t r i n ~ query) int n - J O p t i o n P e n e . s h o w C o n f i m D i e l o ~ i ( n u l l , query, "Yes/No question", JOpt ionPane. Y E S _ N O _ O P T i O N ) ; r e t u r n (n mm 0); }

static v o i d d i s p l a y R e s u l t (String message) JOpt ionPane, s h o w M e s s a g e D i a l o g {null, m e s s a g e , " P r o g r a m Results", JOptionPane. P L A I N MESSAGE) ;

}

This method is overloaded so that it can accept a value of any primitive type as its argument and display it. The method call ZO.displnyResult (-sum i s - + sum) displays a window like the one below.

{

public

static b o o l e a n g e t B o o l e a n ( S t r l n g query, S t r i n g trueAns, S t r i n ~ falseAns) { Ob~ect[] o p t i o n s m {trueAns, falseAns}l int n - J O p t i o n P a n e . s h o w O p t i o n D i a l o g ( n u l l , query, "Select " + trueAns + " or " + falseAns, JOptionPane.TES_NOOPTION, JOptionPane.QUESTIONMESSAGE, null, options, options[0])l r e t u r n (n mm 0 ) 1

The last method for interactive getChoice0. The method call below String[]

is

Method appendOutput0 appends its argument string as a new output line at the end of the output string being formed (outData). String outData is a class data field. Method appendOutput0 is also overloaded so that it will append a value of any primitive type to the output string.

method

coffeeChoiaes

int n w C o f f e e

passes

input

a

m

m {"Regular", "Decal", "Exprosso", "Latte" } ; Z O . g e t C h o i o e ( " S e l e c t a cogfee", coffeeChoices) ;

prompt

and

an

array

of

button

p u b l i c static v o i d a p p e n d O u t p u t ( S t r i n g { o u t D a t a ÷m n e x t L i n e + "\n"; }

labels

(coffeChoices) to method getChoice0. The method call displays the following dialog window.

ne~tLine)

The student can call method displayOutput0 to display the

current output string in a window with a text area (outputArea). Because the text area is part of a JScrollPane object, it will be displayed with scroll bars if it has more than 20 lines or 40 columns. There is also a method clearOutput0 to reset the output string to the null string. A sample output window is show next; the code for method displayOutput0 follows the window.

14

used as a case study to illustrate design techniques and to help students understand new concepts that they are studying in Java. References

[1] Barnes, D. J., Object-Oriented Programming with Java, Prentice Hall, Upper Saddle River, NJ, (2000). [2] Bishop, J., Java Gently, Addison-Wesley Longman, Essex, England (1997). [3] Horrstmann,C., Computing Concepts with Java 2 Essentials, Second Edition, John Wiley & Sons, New York, NY (2000). [4] Koffman, E, and Wolz, U., Problem Solving with Java, Addison Wesley, Reading, MA (1999).

publio mtatlo void displayOutput ( ) {

, 3 T e x t ~ a outputA.~a

-

new

,.lTextArea(20,40); I outputArea, s e t E d : l . t ~ a b l e ( f a l s e ) ; Jffa:o11Pane nc:ollOut new JSc:ol 1Pane (output~ea,

[5] Savitch, W., Java: An Introduction to Computer Science and Pmgrarnming, Prentice Hall, Upper Saddle River, NJ (1999).

o u t p u t A . r e a , setText~ ( o u t D a t a )

Sarol iPaneConstant s. VERTZCAL_SCI~OLLBAR _AB_NEEDED, BurollPaneConstant s. HORIZONTAL_SCROLLBAR AS_NEEDED) ; JOpt ionPane, showMessageDialog (nut1, scrollOut, "Program Results", JOptlonPane. INFORMATZON_MEBSAGE ) ;

[6] Raab, J., Rasala, R., and Proulx, V. K., Pedagogical Power Tools for Teaching Java, SIGCSE Bulletin, 32(3), (Sept. 2000), 156-159. [7] Walrath, K. and Campione, M., The JFC Swing Tutorial: a Guide to Constructing GUIs, Addison-Wesley, Reading, MA, 1998. [8] Wolz, U. and Koffman, E., simpleIO: A Java Package for Novice Interactive and Graphics Programming, SIGCSE Bulletin, 31(3), (Sept. 1999), 139-142. [9] Wu, C.T., An Introduction to Object-Oriented Programming in Java, WCB/McGraw Hill, 1999.

3 Summary The package described gives students easy access to GUIlike interactivity in Java. But the package was intentionally designed to be limited to encourage students to go beyond it and to learn to use the AWT and Swing classes. Because the package is easy to implement and understand, it can be

15

Suggest Documents