Sunteți pe pagina 1din 3

IT501JavaLab2

Making a Calculator Program


Purpose: Using Swing to Build a Calculator GUI.
This is a lab to use your Swing GUI-buildings kills to create a little calculator
program.
You can start by hacking up with your Lab1 MultGui.java Java class le. Again I refer
you to the exercises in Chapter 14 of your book where simple Java Swing programs
are developed. It is valuable tutorial material.
Start with simple program.
Create a new Java Application projectinNetbeans.Callitjlab2.Incase you dont
remember, here are the steps:
Close existing Netbeans projects.
I meant it:closeallyourexistingNetbeansprojects!
Select File/NewProject
Pick Java and JavaApplication,click Next
Calltheproject jlab2.Putitinyour it501 subdirectory.Ifyouhavent
alreadycreatedthatdirectory,youcandosofromthismenu.
Makesure CreateMainClass and SetasMainProject arechecked.
Thenclick Finish
Nowcreateanewclasslecalled Calculator:
Select File/NewFile
Pick Java and JavaClass,click Next
Callit Calculator andclick Finish
Youshouldnowhavetabsfortwosourceles: Main and Calculator.
1Programmingnotes
Javarequiresyoutonameyoursourcecodeleaftertheprincipalclassthat
isinsideit.Ifyoucreateaclasscalled Calculator,itssourcecodewill
beinalecalled Calculator.java.Itscompiledobjectcodewillbein

alecalled Calculator.class.
Wecreatedtwoclassesforthisproject.Theyare Main and Calculator.
Theyliveinsourceles Main.java and Calculator.java.TheMain
classcontainsthe main() methodwhereyourprogramstartsrunning.The
main() methodcreatesa Calculator object,whichcontainsallyour
calculatorcode.The main() method could domore:forexampleitcould
create two calculator objects,whichwouldshowtwocalculatorsonthe
screen!
Javaorganizesitslesinto packages.Netbeansputthestatement package
jlab2 atthetopofeachofyourjlab2sourceles.Anycodeyouaddtoyour
projectshouldhavethesamepackagestatementontop.(Wewontdiscuss
thesemanticsofpackagesjustyet.Butknowyethatthisisessential.)
GettingStarted
Hereisallyouneedtodoforyour Main class.Addthefollowingtothe main
methodinyour Main class:
Calculatorc=newCalculator();
Tostartyour Calculator classyoucaneithercopy-pastecodefromyourprevious MultGui.java lefromjlab1,oryoucanstarttypingfresh.
Inordertogetthecodefrom MultGui,select File / openproject or openrecent
project,andthen jlab1.Navigatedowntothesourcepackages,andopenup
MultGui.java.
Copy-pastethecodeyouwanttokeepintoyour Calculator.java class. Be
suretoretain the packagejlab2 and classCalculator statements!Also
besuretorenametheconstructorto Calculator.Andaddthe implements
statementtotheclassdeclaration.
Nowclosethejlab1project!I mean it.

2Buildacalculator
Yourcalculatorshouldlooksomethinglikethis,withtwoinputareaslabeledX
andY,andaresultarea.Itshouldhavethevebuttonsforthefouroperationsand
aclearoperation(whichsetseverythingtozero).
3

S-ar putea să vă placă și