Java-Express-Intro Java-Examples 0. Objective: Class Constructor File
Java-Express-Intro Java-Examples 0. Objective: Class Constructor File
Objective
Illustrate basic Java concepts such as classes, objects or instances of classes, the simple development tool TextPad; the idea of events on ob ects & how events can be used to trigger responsive actions to the events; basic graphical interface elements li!e textfields & buttons " and the underl#ing $infrastructure ob ects$ li!e $ frames$ %windows& & panels & 'content panes' " used as 'containers' to hold the more directl# user related ob ects li!e fields and buttons( 1. Demonstrate Behaviors
)emonstrate the behavior of a simple calculator in Java: *( ava and Test*( ava %also an analog in Java+cript *(html&( Run Test*( ava( There will be two windows: %,& the dos window for standard output from the program and for error message output and %-& the window created b# the Java program( *ou can maximi.e, resi.e the windows, etc( /bserve the program response to good data and how bad input causes run0time error messages in the stdout )os window %such as: *(actionPerformed %*( ava:12&& 0 but the program does not terminate( 1. Demonstrate Compilation/Execution
Illustrate compiling & running a Java program( The $class$ * 0 that is the calculator ob ect or class 0 is a blueprint describing the structure of the ob ect( In TextPad, the shortcuts ctrl3, compiles the program and ctrl3- execute the class( /bserve what happens when #ou compile *( ava class: it creates a file called *(class( If #ou tr# to execute this class directl# #ou will get an error message $ java.lang.NoSuchMethodError: main$ " which means #ou have to run this class from a main program( +imilarl#, if #ou tr# to execute Test*( ava without first compiling it, #ou will get the error message: $java.lang.NoClassDefFoundError: est!$( /bserve that if #ou compile the main class after first deleting the *(class file, then this triggers compilation of both the main class and the * class %4eep an e#e on the director# where the files are located so #ou can see the compiled class appear(& To execute the program, use ctrl3-( Resi.e the window that appears in order to improve the la#out of its 56I elements( . !a"in# Instances o$ % in &est%
The program %class& Test* creates an instance m of the class *( 7ote the following naming conventions: class * constructor * % & stored in file *( ava
8a!e multiple instances, change the window si.e using the set+i.e method; test the set9isible method; shrin!0wrap the 56I components using the pac! % & method( Test the effect of these methods b# placing a read I/ statement %such as 8#Input(read+tring% && to stall the program execution in order to better understand the method effects( This re:uires the 8#Input class contained in the director#( the other import statements at the top of the program import other ava class libraries %called pac!ages&( 6nderstand the reference to the * constructor in the Test* main program( ;ompare this s#ntax with declarations li!e int 4 < 1 or double pi < 1(,= " except that here it's * m < new *% &( If we had renamed the class * as ;alculator, it could have been more clearl# written as: ;alculator calc < new ;alculator % & corresponding to a class ;alculator in a file ;alculator with a constructor ;alculator % &( Buil' Blueprint $or Calculator class Establish ()I Component In$rastructure* ,( Initiall#: a( 8a!e the class under definition an $extension$ of the window or $J>rame$ class( ?# inheritance this allows the new class to use all the properties and methods %functions& alread# defined for the J>rame class " methods li!e set9isible and set+i.e( b( +et up the window infrastructure in the "constructor" for the class( This includes a so0called panel %JPanel& that #ou can throw %or 'add'& 56I components to, as well as the so0called $;ontentPane$ into which the panel itself is added( -( )eclare, and eventuall# create and add to the window %J>rame extension& the 56I ob ects li!e JText>ield, J@abel, J?utton( +peci$, Event-han'lin# In$rastructure* 1( This includes first indicating %to the compiler& that this class handles button events b# sa#ing it 'implements Action@istener'( =( 8a!e the buttons sensitive to events %li!e being clic!ed& 0 a process called event registration in Java( B( )efine an $event0handling$ routine %method& to ta!e charge whenever an event occurs( Also must tell the environment the class is able to handle a certain class of events( C( Event#handler algorithm " This recogni.es which button caused the event, gets data from the fields, converts the data to integer, do the appropriate arithmetic operation %which the handler can recogni.e b# chec!ing which button caused the event&, then send the results to the output field in the window(
-hen 'evelopin# example* ,( -( 1( =( B( C( F( 8a!e a driver that creates a trivial empt# J>rame: 8a!e the J>rame constructor write to the )os prompt: Add a JText>ield ob ect( Add a button that triggers write to )os prompt: Access data from field and write to prompt as +tring: Erite %altered& input data to prompt as int( >inish up with more fields and computation( It's a windowD It's Alive D It appears( It acts( It reads( It stores( It computes(
a( De$ine a .shell. version o$ the class: )efine G to contain merel# an empt# class " invo!e from appropriate main class " but will get compilation error %chec! error messages& because main class tries to use methods li!e set+i.e that don't exist for this G class " it has to be declared as an extension of a frame %window& class " so it 'inherits' the frame class methods( b( !a"e the .shell. exten' J/rame " ;ompile & run( 5et a shrin!0wrapped window: notice what happens if #ou comment out the pac$ method: the window then maintains the si.e it was set at( Then add an explicit constructor for the class including a little statement to standard output li!e $+#stem(out(println%$I live$&;$ to show it's reall# alive( c. +tart a''in# ()I objects li!e with: $JText>ield text < new JText>ield%-2&;$ 7otice nothing appears in the still shrun! window " that's because we have not done the necessar# preparator# wor! " which here means: ma!ing a panel, adding to the frame's pane %or contentPane&, then adding the text field to the panel( The pane is the part of the frame below the title bar at the top of the frame " to get a hold of it #ou use get;ontentPane%& " specificall# " this(get;ontentPane % & " i(e(: $this instance of the G ob ect's content pane($ Incidentall# note Java's case0sensitivit# & naming spelling conventions( The statements: JPanel panel < new JPanel%&; this(get;ontentPane%&(add%panel&; provide the infrastructure for the 56I ob ects which we then add with: panel(add%text&; Then add the rest of the 56I text fields & buttons: JText>ield text, < new JText>ield%-2&; JText>ield text- < new JText>ield%-2&; JText>ield text1 < new JText>ield%-2&; and the buttons: J?utton but, < new J?utton%$add$&; J?utton but- < new J?utton%$mult$&;
7ote the capitali.ation for the reserved words li!e JText>ield, J?utton, and JPanel( @ater, we'll move the declarations of the fields & buttons outside the constructor so the# can accessed b# the event0handler we will define( >or now, ust add them to the panel( ;hec! the loo! of the window " resi.e to taste " and note the buttons are at this point decorative onl# and do not trigger an# action or response when clic!ed( '. i( ii( iii( iv( v( i( ii( iii( iv( v( +et up the event-han'lin#* register the buttons as event sources give the signature for the corresponding %dumm#& event#handler tell compiler this class handles these events put a message in the handler " compare add v( mult before mult registered ma!e the event0handler recogni.e the event & respond to it but,(addAction@istener%this&; public void actionPerformed%ActionHvent e&I J implements Action@istener +#stem(out(println%$hi there$&; ?e sure the declarations are outside the constructor so the# are global & accessible to the event handler and remove the declarations inside the constructor( Test effect( Erite the conversion line in reverse starting mentall# with the getText method and wor!ing bac! to the declaration( int num, < Integer(parseInt%n,(getText%&& ; To prep the number calculated in the program for output to the JText>ield: n1(setText%+tring(value/f%num1&& Time permitting describe use of tr#Kcatch construction: tr#ILJ catch%Hxception x&I+#stem(out(println%$bad data$&;J to intercept runtime errors resulting from bad input data(
The in0class lab below illustrates man# of the basic concepts in ob ect0 oriented, event0driven, 56I interface design(
Red
Green
Blue
colorMe
reSize
spawn
+ee if #ou can also implement buttons that %,& change the si.e of the window and %-& spawn a new ;olori.er window ob ect( 0ab steps* ,( +et up a driver main program Test;olori.er and a trivial shell for a ;olori.er class( The ;olori.er class should sa# 'extends J>rame' -( Test Test;olori.er for compilation and run time errors( Just shows window( 1( Add a constructor with a println statement( =( Add a JText>ield to the ;olori.er class( This re:uires a JPanel added to a content pane to which the JText>ield is added( )eclare the JText>ield as well( B( Add a button that sa#s $color8e$( C( Register the button with an addAction@istener method( This will also re:uire including the directive 'implements Action@istener' at the class declaration( F( The above will trigger an error without the standard event handler for this t#pe of event: the actionPerformed method( Add a dumm# version of that and test s#ntax with compile( M( >ill out the event handler b# first ust using a println to echo to the standard output window( N( Ac:uire and convert to integer the data from JText>ield( Test conversion with println( 6se the basic s#ntax: Integer(parseInt%7um,(getText % & & ,2( ;reate a ;olor ob ect with the s#ntax: c < new ;olor %R, 5, ?&; where x, #, and . are the converted integers pic!ed up from the JText>ields( ,,( +et the bac!ground color of the JPanel with the panel method; set?ac!ground % c & ,-( )o the resi.e b# reusing the same %first two& JText>ields and the set+i.e method on this instance(
1oints to "eep in min'2 ,( -( 1( =( B( C( 5et #our import statements right( The class and file name should match( Include a main program with the correct signature in the driver program( Hnd statements with semi0colons( 6se 'extends J>rame' to build a window t#pe class( To enliven a button, use: a( implements action@istener b( addAction@istener c( actionPerformed event handler F( )eclare ob ects globall# within class so the# can be accessed b# its methods( M( 7ame newl# created ob ect instances so the# can be referred to b# name( N( Error !essa#es !ista"e* omit 'extends J>rame' semi0colon expected !essa#e can't resolve s#mbol; method set9isible or set+i.e such as if I omitted