Rep Structure & Behavior
Rep Structure & Behavior CS 1316
Popular in Course
Popular in ComputerScienence
This 0 page Class Notes was uploaded by Alayna Veum on Monday November 2, 2015. The Class Notes belongs to CS 1316 at Georgia Institute of Technology - Main Campus taught by Staff in Fall. Since its upload, it has received 14 views. For similar materials see /class/234136/cs-1316-georgia-institute-of-technology-main-campus in ComputerScienence at Georgia Institute of Technology - Main Campus.
Reviews for Rep Structure & Behavior
Report this Material
What is Karma?
Karma is the currency of StudySoup.
Date Created: 11/02/15
Introduction to Java 081316 Representing Structure and Behavior Story K Getting started with Java Installing it Using DrJava Basics of Java It s about objects and classes modeling and simulation what things know and what they can do Examples from Pictures Sounds and music K Things to do to get started Download and install JDK Java Development Kit Download and install DrJava Download JMusic Download the Java source files for class Then tell Java where to find the JMusic and Java source files J Telling DrJava where to find files Eaten 7 RESLIIHCE Lacallnns 3 3 E wwwwww Br wen Brnwser command TunisiarLuzaliun l k JSKM LacatIDn l JSRM cuiisminns Path Extra classpath 7 l1 l ll WEI ll Mama Reset In nefzuns l lilw Parts of DrJ ava k List of class files that you have open Text of your l class file java Where you lt interact with Java Java is objectoriented 95 of everything in Java is an object In objectoriented programming you care about more than just specifying the process You care about who or what does the process And how the overall process emerges from the interaction of different objects Objectoriented programming is The whole idea of objectoriented the world real or imaginary Creates constraints on don t write one big pr In the real world no one knows everything no one can do ever t 39 Each object has it s own things it knows and things it can do about modeling and simulation programming is to create a model of the part of The real world doesn t have one set of rulessteps Y Variables in Java know their types Variables in Java know the kinds of things values they can hold Objects in Java are organized into classes A class specifes what all the objects of that class know and can do All pictures can show themselves even though each picture is different Variables in Java are specific to particular 0 asses We declare a variable to onlyhold objects of particular classes jimmamns Cnnsnle Cnmnlleromnm gtp new p Plccure iv csl l HemasaurcesSwan 1ng p3hawll gt Did you get an error If you got an error as soon as you typed Picture p there are several possibilities All the Java files we provide you are in source form You need to compile them to use them Open Picturejava and click CompileAl You might not have your Preferences set up correctly If Java can t find Picture you can t use it Explaining what s going on gt Picture p lt gt p Every line ends with a semicolon in Java new Y PicturequotDcs1316l 31 95 a Ways MediaSourcesSwa q 39 mpgquot Picture is the name of a class in J gt pshow p is the variable that we re declaring In Java programs You can only use declared variables And you can only declare them once Explaining what s going on new Pictureo creates a gt PICtlJre Pi new picture gt new g The pathname PICtlJre D3051 16 provided as an argument MediaSourcesSwa tells it which picture nJPQquot gt pshow You can always use I and it ll always work on any platform p now refers to the new object instance of class Picture what s going on gt Picture p gt new PicturequotDcs1316 M dif SDU39CeSSWE We ccess what the object MP9 knows and can do With the gt pshow lt doiopemior how 3 refers to wou please execute your show methodquot says Object that Id yo 0 Semicolons or not in DrJava Interactions Pane No semicolon says Evaluate this and show me the resultquot micolon says Treat this like a line of code Panequot just as if it were in the Co e gt P Picture lename Width 480 gtp Dcs1316MediaSourcesSwanjpg height 360 the terms sofar Just about everything in Java is an object n do speci c things obiects are Instances ofa given class in Java All the instances know the same things and can do the same things Variables are Specific to a given class and can only refer to obiects of that type Let s create a sound lljk rhurseq arching D El kmsrhlue D z hurssEZllnn D 112239th quot FIIE ame Files in Me l vi i iiliir s Forquot jammy heachsmzller r gt Saund s new SaundlFlleEhaaseIpchX UElllF Explaining what s going on gt Sou new SoundFileChooserpickAFile gt sp lay We can create an object as we declare the variable FileChooseris an ob39ect that knows how to pickAFieo which pu s up a le picker and returns a strin Instances of the class Sound know how to play thus splay What if we get it wrong gt spta1t l gt sshaiitl Ellul mi slmw39 menu in suiuiir mui armiiiiciits l gt P1Euzeplsyil Error mi iieuiim iii Pict u z mu argiiiiuts mexpicrureptayu gt am 7 Error Unde ned Class annthel nicture 0 An example with Music An example with Music gt importjmuti JMusic pieces gt importjmuti gt importjmmusicdata 3 heed to b gt importjmmusicdata gt Note n1 39 Imponed rSt to gt Note n1 Declare a Note use them 39 variable gt n1 new Note6005 gt n1 new Note6005 gt Create an eighth note gt Create an eighth note at C octave 4 at C octave 4 An example with Music MIDI notes gt importjmuti 0mm gt importjmmusicdata gt Note n1 Note instances have nothing to do gt n1 new Note6005 lt with filenames gt Create an eighth note To create a note you need to know at C OCtave 4 which note and a duration TABLE 21 MIDI we Starting a line With ll creates a comment ignored by Java Making more notes What s going on here gt Note n2new Note640 5 gt Note n2new Note6405 W I k m No 54 gt Viewnotate n 539 ma eano er 6 a i gt V39ew39nOtaten1i another eighth note Error No 39notate39 method in I I There IS an object named View lmlJ UIYlew W h arguments that knows how to notate parts of A JmmusicdataNote music but not an individual note gt Phrase phr new Phrase gt phraddNoten1 gt phraddNoten2 gt Viewnotatephr Constructing M DI le V from Untitled Score Playing with JavaSound Completed MIDI playback Recitation Guide for February 25 2008 Housing Keeping a Homework 5 Due Tuesday March 4 h 1201am midnight b Drop day Friday February 29th c Pm r U D Due 39 39 March 5 h in class same day as Quiz 2 Pair Programming a General overview i Driver types in the code at the computer ii Navigator reviews the lines of code as it is typed in iii More resources 1 httpcowebccgatecheducs1316188 2 httpen wikinerlia nrc wikiPair b Pairprogramming assignments start with homework 6 c Pairs must turn in a pairprogrammer s agreement and post the pair to the coweb pairs page httpcowebccgatecheducs13161035 to have the assignment graded i User attach ii Passwork carmen Problem Solving optional IV Recursion a A recursive method is one that calls itself b llDivide and conquer approach by dividing the problem into smaller and smaller sub problems c In mathematics a recurrence relation is an equation that defines a sequence recursively Sometimes it helps to find the recurrence relation before beginning to program d Example Fibonacci numbers i Defined by the recurrence relation Fn Fn1 Fn2 with F1 1 and F2 1 ii The sequence of Fibonacci numbers 1 1 2 3 5 8 13 21 34 55 89 i How would you approach this I 1 Consider the base cases the smallest problems a The base cases are the problems that we can solve right away For the Fibonacci numbers the base cases are F1 1 and F2 1 b We always need base cases or else we will never have a problem we can solve 2 Break the problem down into subproblems a The problem does not look like our base cases therefore we need to keep breaking it down until it is composed of the base e f V a 9 VI Tree a cases We break the problem down based on the relationship defined by the recurrence relation 3 The code public int fibonacciint i base cases if i i return 1 base case break the problem down not a return fibonacci i l fibonaccii 2 Example Factorial i Defined by the recurrence relation Fn n Fn1 with Fe 1 ii How would you approach this Example Palidrome i A palindrome is a word phrase number or other sequence of units that has the property of reading the same in either direction ii How would you approach this think more conceptually than codewise File InputOutput or File lO pronounced filei oquot General idea Retrieving data input from a file performing some operations and outputting to another file 9 A delimiter is a sequence of one or more characters that separate the entries or tokens in the file Common limiters tquot tab nquot entercarriage return quot comma quot Input File Program Output File O perations O perations O perations O perations I space hfml Code example httpiava sun II I 1 IL I I l LUI uuu 1 Lu data structure A tree is acyclic without cycles graph i BST Binary Search Tree root no parents leafno children Recitation Guide for April 7th 2008 Housing Keeping a Homework 7 due Wednesday April 9 h b Exam 2 in class Friday April 11 h c Quiz 4 in class Friday April 18 h d Quiz 3 solution posted to Tsquare Grades and papers should be returned the latest on Wednesday Two weeks from Wednesday for regrades Regrades to Dawn UMLUnified Modeling Language a Individualdiagram Name of the class gt person int dateOfBirth lt Methods or String sex operations What eat the instance gt work knows how to do pay0 b Specializationlnheritance relationship Person int dateOfBirth Strin g sex ltl ea t work pav0 Doctor degree specialization doDoctorStuff Doctor is a subclass of Person Therefore Doctor is a specialization of Person Instance variable attributes or fields What the class knows Visiblity Table Private Bidirectional relationship Flight plane 0 assignedPlang assignedFlights 01 int flightNumber Date departureTime Minute flightDuration String depa rtingAirport String arrivingAirport StringairPlaneType MPH maximumSpeed Mile maximumDistance String taild delayFlight Minute numberofMinutes getArrivalTime A bidirectional association is indicated by a solid line or a line ending in arrows on either side between the two classes At either end of the line you place a role name and a multiplicity value The Flight is associated with a specific Plane and the Flight class knows about this association The Plane takes on the role of quotassignedPlanequot in this association because the role name next to the Plane class says so The multiplicity value next to the Plane class of 01 means that when an instance of a Flight exists it can either have one instance of a Plane associated with it or no Planes associated with it ie maybe a plane has not yet been assigned The figure also shows that a Plane knows about its association with the Flight class In this association the Flight takes on the role of quotassignedFlightsquot the diagram tells us that the Plane instance can be associated either with no flights eg it39s a brand new plane or with up to an infinite number of flights eg the plane has been in commission for the last five years Multiplicity Multiplicity Table Multiplicity value Meaning 01 Zero or one 1 One only 0 Zero or more Zero or more 1 One or more 3 Three only 05 Zero to Five 515 Five to Fifteen Unidirectional relationship In a unidirectional association two classes are related but only one class knows that the relationship exists BankAccount OverndrawnAccountsReport overdrawnAccountK v Date generatedOn String owner Dollar balance refresh depositDollar amount withdrawalDollar amount A unidirectional association is drawn as a solid line with an open arrowhead not the closed arrowhead or triangle used to indicate inheritance pointing to the known class Like standard 39 39 the uni 39 39 39 multiplicity value but unlike the standard bi quot 39 39 39 39 the uni quot 39 39 includes a role name and a association only contains the role name and multiplicity value for the known class In our example in the figure the OverdrawnAccountsReport knows about the BankAccount class and the BankAccount class plays the role of quotoverdrawnAccountsquot However unlike a standard association the BankAccount class has no idea that it is associated with the OverdrawnAccountsReport For more information see http ihm quot 39 worksrationaibrarvcontent 39 39F39 quotIAbel u Story o Structuring images into scenes Vermont Representing hneahtythrough eierhehts order Animation through rehdehh and data structure tweahhg ord r ltlt me a o 2 N n m e 3 i to S 2 S e if 0 e to I rsiori 3 Aiiowmg both if a sthgie hs introducing subciasses and superciasses 081316 Representing inciuding abstract masses Structure and Behavior PaSSing aturtie aiongtor processthg Verettahzt Creatingtrees ottrhages Mahhgthe branches do something Bui ing a Scene Use an array gt Picture 1 myarray new Pictureisi 39 ompUter graph39cs prOfess39onals work at two gt myarray new Picturetrhechuusergetmemapathnhattehag levels gt myarraytnew PicturEFiiEChuusEr getMedtaPath narnarahag gt myarray2new PicturEFiiECnuusergetMediaPathC fiuWert hag They denquot 39quotd39V39dua39 Charade and erred quot gt myarray3new PitureFiiEChuusEr gEtM EdiaPathC fiuWerZjpg Charade Iquot ierms 0f Plxe 5 gt myarray 41hew PicturEFiiEChuusEr getMEdi Pathnbuttemytpgnt But then most oftheir work is in terms ofthe scene gt Picture ba kgmund HEW Picturew mnn gtrur thtt u ilt 5 w myarraym saie 5 cum pusemachgruuhumum at Combinations of images characters effects on cters gt backgruund snDWOt chara c To describe scenes they o en use linked lists and trees in order to assemble the pieces Veahrwe uuid But infiexibie Hard tn inSEFL deiete Version 1 Using a linked list PositionedSceneElement Okay so we ll use a linked list But what should the ordering represent Version 1 Linear39ty The order that things get drawn le toright Version 2 Layering The order that things get drawn bottomtotop is Exampie Using hrum akey tu umpuse just u further h at it What this looks like f Slightly different ordering Put the doggy between tree2 and tree3 gt tree3setNexthouse Yes we can put tree2setNextdoggy gglg leents in doggysetNexttree3 one line gt bg new PictureFileChoosergetMediaPathquotjungl eJ39pgquot gt tree1drawFromMeOnbg gt bgshow PositionedSceneElement public class PositionedSceneElement the picture that this element holds W Pretty darn similar to our music linked lists private Picture myPic N the next element in the list W private PositionedSceneElement next Constructor I Make a new element with a picture as input and next as null param heldPic Picture for element to hold W public PositionedSceneElementPicture heldPic myPic heldPic next null Linked list methods N Methods to set and get next elements param nextOne next element in list W public void setNextPositionedSceneElement nextOne thisnext nextOne Again darn similar public PositionedSceneElement getNext return thisnext k K Method to draw from this node on in the list using Traverse n bluescree Each new element has it39s lowerleft corner at the the quotst lowerright of the previous node Starts drawing from left bottom param bg Picture to draw drawing on u Traversing the public void drawFromMeOnPicture bg St in orderto PositionedSceneElement current draw the scene int currentX0 currentY bggetHeight 1 is called I rendering the current quot5 scene Realizing while current null the picture currentdrawMeOnbgcurrentX currentY rrentX currentX currentgetPicturegetWidth current currentgetNeXt described by the data structure K W Drawing the individual element Method to draw from this picture using bluescreen param bg Picture to draw drawing on param left x position to draw from param bottom y position to draw from w private void drawMeOnPicture bg int left int bottom Bluescreen takes an upper left corner thisgetPicturebluescreenbgleft bottomthisgetPicturegetHeightO W Core of the Traversal current this while current null Treat the next two lines as blah blah blahquot currentdrawMeOnbgcurrentX currentY currentX currentX currentgetPicturegetWidth K current currentgetNext K W Generalizing o Reconsider these lines gt tree3setNexthouse tree2setNextdoggy doggysetNexttreeB o This is actually a general case of Removing the doggy from the list Inserting it aftertree2 Removing the doggy gt tree1setNexttree2 tree2setNexttree3 tree3setNextdoggy doggysetNexthouse gt tree1removedoggy gt tree1drawFromMeOnbg Putting the mutt back gt bg new PictureFileChooser getMe diaPathquotjunglejpgquot gt tree1insertAfterdoggy gt tree1drawFromMeOnbg F Melhudluiemuvenudetiumli tlxmglmks Removmg an annmnnaten Paiam eeeiernertterernevenernnat element 1 d d d Pu iic vui iemquPusiliune SceneEiemen nu El from the st ntnaae this t system out pimlinC i cant reinqu tne inst nude nurn tnenat Note Haw Wuu u return you r mnv tne 5 E Ememm PusiliunedSceneElemem current t ne list me n Wntie tnere are more nudeslu consider wnne current eetNektoi nuii Error checking and printing lM Method to remove node from list xing links appropriately param node element to remove 39om list public void removePositionedSceneElement node i tttcunent eetuekto neeex if quot0d5th 5 n Snnpk make nude snekl he tntanekt current aetuekttneee eetuekto iiMakelhisnudEpuinHu nothing Systemout rIntln I can t remove the rst node neee aetuekttnun return t eturn cunent cunent eetuekto i j Insert the input node alter this nod The Removal Loop InsertAfter k param node element insert lter this Posttion edSceneElement current this While there are more nodes to consider ublic void Wh e current gewexto t W E Chem pinsertAlterPositionedSceneElement H is this t7 gEtNexto because We WW ammth node if current getNextO quot node quotEm UP We 5 5 involved in creating 39 Simply make nodeg ext be m Next oerore msenaemmo ll Sa e what this currently points at current setNekttnode getNektOt Make this node pointto nothing node setNekttnuii return i current current getNextO it not keep Searching i PositionedSceneElement oldNext his etNext this setNextnode nodesetNextoldNext Animation Changing a structure rendering n n We can use what we just did to create animation Rather than think about animation as a series of frames Think about it as Repeatedly Change a data structure Render draw while traversing the data structure to create a frame AnimatedPos39 nedScene pupnc ciass AnimateuPusitiuneuSEEnel f A Frain eSeuuence rur stunng tne rrarnes n FiaineSeuuence rrarnes p We ll need tn keep track Elf the elements Elf the Scene n PusitiunedSEEnEElEment treei treez trees nuuse muggy uuggyrnp public void setUp frames new FrameSequencequotD lTempquot n g u p Picture p null Use this to ll elements 39 39 p new PictureFileChoosergetMediaPathquottree the animation tbluelpgu ree1 new PositionedSceneElementp new PictureFileChoosergetMediaPathquottree berJ39PQ tree2 new PositionedSceneElementp p new PictureFileChoosergetMediaPathquottree bluequot39quot tree3 new PositionedSceneElementp p new PictureFileChoosergetMediaPathquothouse bluejpgquot house new PositionedSceneElementp p new PictureFileChoosergetMediaPathquotdog bluequot39quot doggy new PositionedSceneElement 39 doggyflip new PositionedSceneElementp ip l Render the rst frame public void make framesshow First frame Picture bg new PictureFileChooser getMediaPathquotjunglejpgquot tree1setNextdoggy doggysetNexttree2 tree2setNexttree3 tree3setNexthouse tree1drawFromMeOnbg K framesaddFramebg Render the doggy moving right ll Dog moving right new PictureFileChoosergetMediaPathquotjunglejpgquot tree1removedoggy39 tree2insertA erdoggy tree1drawFromMeOnbg framesaddFramebg new PictureFileChoosergetMediaPathquotjunglejpgquot tree1removedoggy tree3insertA erdoggy tree1 rawFromMeOn g framesaddFramebg framesaddFramebg Dog moving le bg new PictureFileChoosergetMediaPathquotjunglejpgquot tree1removedoggy houseinsertA erdoggyflip tree1drawFromMeOnbg framesaddFramebg bg new PictureFileChoosergetMediaPathquotjunglejpgquot tree1removedoggyflip tree3insertA erdoggyflip tree1drawFromMeOnbg framesaddFramebg bg new PictureFileChoosergetMediaPathquotjunglejpgquot tree1removedoggyflip tree2insertA erdoggyflip tree1drawFromMeOnbg framesaddFramebg bg new PictureFileChoosergetMediaPathquotjunglejpgquot tree1removedoggy flip tree1insertA erdoggyflip tree1drawFromMeOnbg framesaddFramebg Version 2 Layering gt Picture bg new Picture400400 gt LayeredSceneElement tree1 new LayeredSceneElement new PictureFileChooser getMediaPathquottreeblue jpgquot1010 gt LayeredSceneElement tree2 new LayeredSceneElement new PictureFileChooser getMediaPathquottree blue jpgquot10010 gt LayeredSceneElement tree3 new LayeredSceneElement new PictureFileChooser getMediaPathquottreeblue jpgquot200100 gt LayeredSceneElement house new LayeredSceneElement new PictureFileChooser getMediaPathquothouseblue jpgquot175175 gt LayeredSceneElement doggy new LayeredSceneElement new PictureFileChooser getMediaPathquotdogblue jpgquot150325 gt tree1setNexttree2 tree2setNexttree3 tree3setNextdoggy doggy setNexthouse K gt tree1drawFromMeOnbg gt bgshow F First version of Layered Scene Reordering the layering gt housesetNextdoggy doggysetNexttree3 Basicallywe re tree3setNexttree2 reversing the St tree2setNexttree1 gt tree1setNextnull gt bg new Picture400400 gt housedrawFromMeOnbg E I l gtbgshow J K f Reordered relayerecl scene What s the difference o Ifwe were in PowerPoint or Visio you d Thinkabout say that we changed the layering involved in Bring to front These commands are t39 n quot actually changing the 2111th send to baCk ordering of the layers in the reverse a Bring forwardquot list of things to be redrawn lIst u Change the ordering in the 39 Send backward quotst Render the scene 39 Now it s a different layering LayeredSceneElement Constructor I public class LayeredSceneElem ent Make a new element with a picture as input and the picture that this element holds I next as null to be drawn at given xy param heldPic Picture for element to hold private Picture myPic param xpos x position desired for element param ypos y position desired for element the next element in the list I public LayeredSceneElementPicture heldPic int xpos int ypos private LayeredSceneElement next myPic heldPic next null The coordinates for this element X xpos I Y ypos private int x y j K Linked List methods We can sort of assume these now fig quot public void setNextL ayeredSceneElement nextOne thisnext ne 39 public LayeredSceneElement getNext0 return thisnext Methudtu urawtrerntnrs name an mine ii51 usrne biuescieen Starts u Pavam bu Picture tu draw u r tawny nun rertuutum Travers ng vawne en pubiic Vuid diaWmeM 20HPicture bgH terereusEereeremen current this Whiiecunenti nuii i current drawMeOMbEL current cunenieewexm i i Meineu in urawtrerntnrs picture using biuescreen Paiam bu Picture in draw drawing an r Private vuid diaNMeOnPictuie bgH tan getPictuVEO biuescieenmu xwr i Linked list traversals are all the current this while current currentdrawMeOnbg current currentgetNext null e neereetne n51 s1amnu at tne Do ng a andiatumtheiaseiermmmtneiist TneiasteienentbecurmstneFiRSTeienent reve rseo Levine net and THiS puintstu nuii Pubiic LavereuSceneEiernent yweisEOi LareiedSceneEiermmiweisEd te r H Hermie tnenra nude euisrueine ieup iweised thisias10r tan iemeOeeism Wmie msuethxtOi nuii i term thisia or tnrerernmeaem reversed add emwr r n NW put tne neau urine ere n51 untne enu at n tne reversed r51 iweised and mQr ii At in paint reversed ii is tne neae mine net return iweised i Getting the last W Return tne iast eiernent in the hat m pubiic LayeredSceneEiement iast LayeredSceneEiement current Basicaiiy it s a urrent hiS W 5 5 Whiie current getNexto i nuii WE SE current current getNextO return current Adding to the end M Add he input node atter he last node in thislist param node element to insert aite t 39s M public void addLayeredSceneElement node this astinsertAiternode Pretty Easy nun7 Find tne iast nu insEVtAftErO Does 39t work9 ew PlcluVEMDD ADD gt Plclule b gt tayeredSeeneElernent treel new tayeredSeeneElernent new PletureFllecneesergetMedlaPatnmreebluelpg y u u gt tayeredSeeneElernent treez new tayeredSeeneElernent new PlcluleFlleChuusel getMedlaPatnmreebluenag AELlEI gt ayeledSceneElemenl neuse new tayeredSeeneE rnent new PlcluleFlleChuusel gemledlaPalhf huuserbluelpg l l gttreel selNexl leeZ treez selNthuuse gtLayeledSceneElemenl rey treel reyerseo gt rey drawrrernlweonbgr gt as aw l gtHald b tell nerntne layenngelers eneek anulhelway gt rey huuse rue gt rey treel talse Let s add th39s up then while this getNext null Sn new expenslle ls tnls lebb7 We gm tnrbugn tnls leeb once temp hisast rereacn elernentln tne llst thisremovetemp Fur eacn nude we rlnd tne laszo wnlcn ls enoznertrayersal reversedaddtemp And wnen we add we knew tnatwe db enotnerleszo wnlcn ls anomertraversal Total cost For each of the n nodes THEE reversing takes two traversals 2n 5 a gt 0n2n gt 0nZ better way Version 3 A List with Both 0 Problem 1 Why should we have only layered scene ele ts ments or positioned scene elemen 0 Can we have both 39 SURE lfeacll element knows how to draw ltselfl But tney took dlrrerent pararnetersl yered gettnelr x y bassed ln tworks lr we alwa s pass ln a lunletnat s set to tne rlgnt placeto draw lr lt s posltloned and let tne layered ones do Whatever they wantl 0 Problem 2 Why is there so much duplicated code Why do only layered elements know lasto and add0 Using Superclasses o What we really want is to de ne a class SceneEement That knows most of being a picture element It would be an abstract class because we don39t actually mean to ever create instances of THAT class 0 Then create subclasses SceneEementPositioned an d S ans 5 5 e39d actually use these Class Structure Abstract class SceneEemenl lt knows lts Plcture myPlc and lts ext SceneElement lt knows how te getSe next te reyerseo and lrlsertAftErO and te drawFrumMeOno ltdeflnes draWWltMtthle but leayes ltrer lts subclasses db rnblete class derlnes Class Structure 5m and benaylbr Abstract class SceneElement tnat subclasses it know lts Plclule myPlc and V Wm WM new it know hnwlu gelset newl lu reyerseo and lnsenA elO andlu diawFlumMeOnO and Tne subclasses We saytnat tne inherit data and drawvwndunle subclasses rnetneds rrern extend tne superclass suberclass Class SCSNSEWSMWSM class SceneEemeanosllloned lt knows lts pusrtlnn w lt knows how te draWWlthturtle lt knows how te draWWlthturtle by rneylng te x y tnen drubban KUsing the new structure f public class MultiElementScene Rendering the scene public static void mainString args FIVt equot39 use thi for lling the Odes node1setNextnode2 node2setNextnode3 ic ure nu p node3setNextnode4 node4setNextnode5 p new PictureFileChoosergetMediaPathquotswanjpgquot SceneElement node1 new SceneElementPositionedpscale025 NOW let39s see it p new PictureFileChoosergetMediaPathquothorsejpgquot 39 39 SceneElement node2 new SceneElementPositionedpscale025 P39Cture b9 new P39Cture6001600v p new PictureFileChoosergetMediaPathquotdogjpgquot node1drawFromMeOnbg SceneElement node3 new SceneElementLayeredpscale051050 bg39ShOWO39 p new PictureFileChoosergetMediaPathquotflower1jpgquot SceneElement node4 new SceneElementLayeredpscale051030 p new PictureFileChoosergetMediaPathquotgravesjpgquot SceneElement node5 new SceneElementPositionedpscale025 f Rendered scergTe SceneElement I An element that knows how to draw itself in a scene with a turtle H public abstract class SceneElement In the picture that this element holds u protected Picture myPic I the next element in the list any SceneElement H K protected SceneElement next I Method to draw from this node on in the list For positioned elements compute locations Each new element has it39s lowerle corner at the lower Lmked Llst methods m i rIg of the previous node Starts drawing from le bottom drawFromMeon lparam bg Picture to draw drawmg on pubic void drawFrom MeOnPicture bg SceneElement current Methods to set and get next elements lStarttheXatthele Start the Y along the bottom param neXtone neXt element In St int currentX 0 currentY bggetHeight 1 Turtle pen new Turtlebg public v0id setNextSceneElement nextOne pensetPenDownfalse Pick the pen up thisnext nextOne I current this By declaring while current null ll Position the turtle for the next positioned element be penmoveTocurrentXcurrentY currentgetPicturegetHeight SceneElement pensetHeading0 it can be any currentdraw thpen kgid SUbCIaSS currentX currentX currentgetPictureget dth O K SceneElement current currentgetNext everything to public SceneElement getNext return thisnext KBut SceneElements can t drawWith SceneElementLayered public class SceneElementLayered extends SceneElement I Use the given turtle to draw oneself The coordinates for this element at param t the Turtle to draw with PriVa eivaY I l Make a new element with a picture as input and next as null to be drawn at given xy pubhc abstract vod drawWth Tu rtle t39 param heldPic Picture for element to hold I param xpos x position desired for element N0 In the superClass agparam ypos y position desired for element public SceneElementLayeredPicture heldPic intxpos int ypos myPic heldPic K j K next null x xpos Y YPOS public class SceneElementPositioned K extends SceneElement SceneElementLayered Make a new element with a picture as draWWIthO SceneElementPOSItIoned Intuit and H nex as nu H param heldPic Picture for elementto hold Method to draw from this picture I param pen Turtle to draw with purb llojSSeElementPosrtIonedPIcture myPic heldPic next null public void drawWithTurtle pen We just ignore the pen39s position I pen I moveTo X 39Y getgfadmto rrtaflivufr tfentghuepifrutrjerawin pendropthis getPictureO H p p g public void drawWithTurtle pen pendropthisgetPicture k j g Version 4 Trees for defining K scenes The Attack of the Nasty Wolvies 0 Not everything in a scene is a single list 39 Think about a pack of erce doggies er wolves attacking the quiet village in the forest 39 Real scenes cluster o Is it the respons bility of the elements to know about layering and position 39 Is that the right place to put that know hotW o How do we structure operations to perform to sets of nodes K 39 For example moving a set of them at once K a 39 Closer Then the Hero Appears And the Wolvies retreat What s underlying this o This scene is described by a tree Each picture is a BlueScreenNode in this tree Groups of pictures are organized in HBranch or VBranch Horizontal or Vertical branches The root ofthe tree is just a Branch The branches are positioned using a MoveBranch k Nesting is a tree relationship Lev k Level1 vertical horizontal e1 Top canvas Level 1 horizontal Level 2 vertical 7 Level 2 W horizontal Labeling the Pieces Branch root MoveBranCh t0 MoveBranch to 1050 300450 VBranch with BlueScreenNode wolves lBranch with BSN v ovi 10400 HBranch with 3 BSN houses and a t VBranch with 3 BSN houses k 11 It s a Tree of instances39 Branch rcicit MoveEranch tci MDVEEranchto MDVEEranchto swam luau imam HEranch with 3 BEN hciuses and a VEranch with H Branch with SEN ElueScreenNode trees s varanchwitha ESN hciuses The Class Structure d another tree 1 es o DrawableNode knows only next but knows h wto do everything that our picture linked lists do insertA er remove last drawOnpicture E e ing else is a subclass ofthat o PictNode knows it s Picture myPict and howto drawWithturtle by dropping a picture reenNode knows how to drawWithturtle by using bluescreen The Class Structure another tree 2 branches 0 Branch knows its children a linked list of other nodes to draw It knows how drawWith by 1 telling all its children to draw 2 then telling its next to draw 0 A HBranch draws its children by spacing them out horizontally o A VBranch draws its children by spacing them out vertically Note This is not DrawableN cine the same asthe The ai uws HE anch VEranc r h MEWS W ElueScreenNode Knows hciw Knows hciw tci draleth venlcally Knows hciw tci draWWlth as bluescreerl h horizontally pcisiticin then draleth The Class Structure Diagram i sceneo lea MEWS next represenlJaya stiuctuiel extends sci go PlEtNDdE ur WE nasal Knows myPlct Knows chlldren MEWS WW draleth MoveErarlch Using these Classes When doggies go bad39 publlc classWullAllackMuylel p The iuut utthe scene data structure Branch scenePuut r FrameSequencewhere the anlmatlon 15 93 These are the nodes that change durlng the FrameSequence names r v The nodes we needlu track between methuds lucal rnethciu ccintext MoyeEranch wuhentiywulneheat here Setting up the pieces W T Setup all the pieces or the tree n publlc Void setUp Picture wolr new PlctureFlleChooser getMedlaPath doge bluelpg Picture house new PlctureFlleChooser getMediaPatht house bluelpg Picture tree new PlctureFlleChooser getMediaPatht tree luelpg i Picture monster new PlctureFlleCh005er getMedlaPathC monStel efaceSlpg Making a Forest lMake the fore MoveBranch on the botto een BlueScreenNode treenode for int i0 i lt 8 i ll insert 8 tree treenode new BlueScreenNodet trees addChildtreenode forestaddchildtrees s reescale0 HBranch trees new HBranch50 ll Spaced out 50 pixels be 5 st forest new MoveBranch10400 ll forest m Make attac g wolves Make the cluster of attacking Wolv Wolfentry new MoveBrancn OSO Starting position BiueScreenNode woit2 ne woits new BlueSc wolves addChild woifi wolves addcniidtwoimi wowes addChil woit wolfentry addChildMolves w BlueScreenNodewoif scaie reenNodewolf scaie VBranch wowe new VBrancnaoi space out by 20 pixels between BiueScreenNode woifi new BlueScreenNodewoif scaie o o 0 5 5 5 Make retreating wolves ll Make the cluster of retreating 39Wolv quot wolfretreat new MoveBra wolf1 new BluescreenNodewolfscale05 ip0 wo new BluescreenNodewolfscale05 ip0 wolf3 new BluescreenNodewolfscale05 ip0 wolvesaddchildwolf1wolves addChildwolf2 wolvesaddChil wolf3 wolfretreataddchildwolves es nch40050 ll starting position wolves new VBranch20 ll space them out by 20 pixel between It takes a Village Make tne village MuveEranch village new M nsn hhuuses new Haransnmnt Huuses are 4D pixeis apart acmss EiueSEreenNude nuns nuusE scae D2 eenNDd Nu u i 25 Blue screenN nee huu Blue screenNude huuse saieEI 25 El eSUeenNude e esaeu 25 vhuuses adanilmnuusEA vhuuses addChildmuusEE vhuuses a cniiene e u u e hhuuses adaniWnuusei hhuuses adanildnuusEZ hhuuses addChilmnuusEL hhuuses addChiidWhuuses Yes a verancn can be a child at an HEranchi village adaniidmhuuses eEranch UU AEU Village un butturn Making the village s hero Make the monster hero new MoveBranch400300 BlueScreenNode heronode new BIueScreenNodemonsterscale075fli p heroaddChildheronode Assembling the Scene Assemble the base scene sceneRoot new Brancho ll sceneRootaddChildforest 335 Then itwiii get rendered first sceneRootaddChildVIllage sceneRootaddChildwolfentry WulfrEtrEat and munstEr7 They ll get inserted intu tne scene in tne middle ertne muvie Trying out one scene Very important for testing M Renderjust the first scene Ml public void renderScene Picture bg new Picture500500 sceneRootdrawOnbg bgshow Okay that works f Rendering the whole movie M Render the whole animation Ml public void renderAnimation frames new FrameSequencequotDTempquot framesshow Picture bg Wolvies attack for 25 frames First the nasty wolvies come closerto the poor village Cue the scary music for int i0 ilt25 i Render the frame bg new Picture500500 sceneRootdrawOnbg framesaddFramebg Inchbyinch er 5pixels by 10 pixels they creep closer Tweak the data structure wolfentrymoveTowoIfentrygetXPos5wolfentrygetYPos10 Our hero arrives In frame 26 Now our hero arrives thisrootaddChildhero Render the frame bg new Picture500500 sceneRootdrawOnbg framesaddFramebg K Exit the threatening wolves enter the retreating wolves Remove the wolves entering and insert the wolves retreating thisrootchildrenremovewolfentry thisrootaddChildwolfretreat Make sure that they retreat from the same place that they were at wolfretreatmoveTowolfentrygetXPosO wolfentrygetYPos Render the frame bg new Picture500500 sceneRootdrawOnbg framesaddFramebg 14 The wolves retreat r more qulckly Maklng the Mowe Now the cowardly wolves hightail it out of there Wecome to DrJava Cue the triumphant music gt u mm n new mm n forinti0 K10 i vvalll nu m wamsetUp wamrenderSceneO Renderthe frame b9 W Picture500500 gt wamrenderAnimationO sceneRootdrawOnbg framesaddFramebg There are no frames to show yet When you add a frame it Tweak the data structure Will be shown wolfretreatmoveTowofretreatgetXPos 10 wolfretreatgetYPos 20 gt wamreplay l J K The Completed Movie Okay how d we do that o This part is important a 0 Remember You have to do this for your animation with sound 39 You need to understand how this actually works 39 And by the way there s a lot of important Java in here K DrawableNode The root of the K DrawableNodes know how to be class structure chained into linked lists M I N x and brames m the Methods to set and get next elements param nextOne next element in list abstract public class DrawableNode L The next branchnodeMateverto process public void setNextDrawableNode nextOne public DrawableNode next this39next nextone Constructorfor DrawableNodejust sets next to null public DrawableNode getNext I public DrawableNode return thls39neXt V J x DrawableNodes know how to draw themselves and list the gwen turtle to draw une elf param t the Turtle to draw wtth n An abstract method ts tune that superclasses MUST overrideithe have to pmvtue then own nn piementattun of wt abstract pubhc vmu urathth ume t r Nu may in the superclass f Draw an the gwen ptcture pubhc vmu arawontprcture bg Turtle t new Turtleb tsetPenDuwnUaise thts uraththa linked list stuff 1 Memo mm Mt m tst one We mowth 39aram We who woman ist mama mmwaormatnm mot 39tnsenm mvulnade was We 39aram We who mamas mamammmowatmtnaaex notquot me rm tantrum tst We DrawabieNade amt want mvm Mt mum rm Mt wins tst 39aram We who mamas Whiterum mwatnm nadeX tms ago imenMertnade DrawableNodes know all that PictNode is a kind of DrawableNode PictNode is a class representing a drawn picture node in a scene tree m public class PictNode extends DrawableNode In The picture I39m associated with Picture myPict To construct a PictNode Make me with this picture param pict the Picture I39m associated with at public PictNodePicture pict super Call superclass constructor myPict pict if yuu want u caH the superciass s constructun yuu must an t that first construct a DrawableNode How P tNodes drawW h Use the given turtle to draw oneself param pen the Turtle to draw with H public void drawVWthTurtle pen pendropmyPict BlueScreenNodes know nothing new BlueScreenNode ts a PtctNodethat composes the ptcture usmgthe bluescreeno method m Ptcture ouohc class BlueScreenNode extends PrctNooet Construct does nothmg fancy n publtc BiueScreenNodePtcture ox suoenot Call superclass constructor BlueScreenNodes draw d39fferently Use the given turtle to draw onesef Get the turtle39s picture then bluescreen onto it param pen the Turtle to draw with public void draw thTurte pen Picture bg pengetPicture myPictbuescreenbg pengetXPos pengetYPos Branches add ch39ldren pubnc ciass Branch extends DrawaoieN ode t p A itst ctr cntimen to maw pubitc D rawaoieN ode cniidre t p Construct a branch wttn cntimen and next as nuii n pubitc Branch t supertr Caii superciass constructor chiidren nuii But because theyre cntimen and as next Hence they brencn Hence a tree Adding children to a Blanch Method to add nodes to children I public void addChidDrawabeNode child if children null childrenaddchid e children child Drawing a Branch Ask aii our cniidren te draW tnen iet next mew Pararn pen Turtie te drawwitn t puptc void mewmtnrrunte pen DrawabieNude current cnrmen lTeiitne cniidrentu mew wniie current i nuiit current draWV nGlen current current eetNextOt lTeii nrr next te mew trttntseetuextm nuii this eetNextO mewwtntnenm HBranch Horizontal Branches pubnc ciass HBranch extends arancnt p anzbntai gap between cntimen n tnt gap r Construct a branch wttn cntimen and next as nuii n pubitc H Erancnint spacing supero Caii superciass constructor gap 7 spacing i HBranch draws horizontal children Ask aii our cniidrentu draw tnen iet next mew Pararn pen Turtie tn drawwitn t Pubiic void draWVitnUurtie pen DrawabieNudecurrent cniidren H Have Mr cniidren draw wniie current current draWW nPent pen rnuveTupen getXPusOtgap pen detVPuSO gt current current detNextOt it Have mr next mew trttntseetuextOt nuii ttnts eetNextO dravwvrtn len r Justdraws ata different pesttten Recitation Guide Wednesday May 23 2007 A Handle Installation Issues a If necessary quickly run through how to set up Dr Java b Try to handle individual issues as quickly as possible If necessary employ the help of B Quiz 1 a students to help out with a general walkthrough Feedback b Comments on length difficulty level preparedness going in C Homework 2 and introduction to Turtles a Homework 2 is due on Friday TSquare is still in the process or being set up Email will be our backup method Go through Homework 2 s assignment description answer any questions Teach students how to use FileChooser setMediaPatn quotC csl3l 6MediaSources FileChooser getMediaPatn quotswanjpgquot i Remember that the Media Path needs to be set ONLY ONCE on a computer Please tell students how the inclusion of FileChooser setMediaPatn and in homework is incredibly annoying for grading homeworks World and Picture canvas i Remember that Turtles need to be given either a World or a Picture blank or not to play in ii Turtles default to invisible World w new World iii Turtle default to visible Picture canvas new Picture 500500 iv Turtles default to invisible Picture swan new Picture FileChoosergetMediaPatn quotswan jpgquot d Turtles i World w new World Turtle t new Turtlew tsetVisibletrue set t to be visible ii See TurtleSquares java for a good example of how to use Turtles to drawboxes iii Other useful methods in SimpleTurtle java 1 PEDUP l 2 penDown getHeading setHeading defaults to 100 pixels forwardint pixels getXPos forward lOUlgtJgtLJ Story Graphical User Interfaces are Trees Building a Graphical User Interface in Java Adding pieces to a JFrame Buttons panels etc Constructing a GUI is building a tree Layout managers CS1316 Representing Layout managers are GUI tree renderers Structure and Behavior Making GU39S do something Listeners Building a musical instrument Old style Java K Abstract Window Toolkit AWT Swing javaxswing Original Graphical User Interface GUI Classes Repacement5 for most AWT components Container Objects Frame Main window with title and border JBunon Bunon Images and teXt Panel groups components JFrame Frame main window 39 Canvas create custom components JPanel Panel container Input and Output Classes 39 Label not editable text New GUI components 39 Button pushing fires an event Trees JTree Checkboxes and Radio Buttons Split pane Jsplitpane 39 TextField input and output of text 39 TextArea input and output of multiple lines of text Table 39 JTable 39 List Select one or more items from a displayed list Supports multiple looks and feels 39 Choice Select one from a drop down list J K Java also called metal Windows Mac Motif Swing TopLevel Containers Swing General Containers JFrame main window with ti le maybe a menu bar JPaneI group components 7 and the ability to minimize maximize and close the I window Helln Wnrld JApplet main window for an applet Inherits from javaappletApplet JDialog popup window for simple communication with the user Like the JFileChooser Working with a JFrame Pass the title when you create it JFrame frame new JFramequotFrameDemoquot Add components to the content pane JLabel label new JLabelquotHello Worldquot framegetContentPane addlabel BorderLayoutCENTER Set the size of the JFrame framepack as big as needs to be to display contents Display the JFrame framesetisibletrue display the frame JFrame Options When creating a GUI application Have your main class inherit from JFrame So it is a JFrame Or have your main class inherit from JPanel And create a JFrame in the main method Create the main class object Add the main class object to the content pane of the JFrame If your class inherits from JPanel It can be reused in another application Even an applet w Ul components and layoutmanagers rendering GU ITree l importjavax ewlngr Need this to reach Swing eombonents Class publleclass GUltree extends dFrarne public GUltreeOl super GUlTree Example Putin a panel wltn a label in it JPanel anell new JPanelo thllsgetCorlterlLParleO addtbanell a 39 new JLabelquotThl5 l5 panel llllt panelleqeuabelt 39 V lt7 9 a 7 utlrlyarlother panel with two buttons ln it Welcometo DrJava JPanel panelZ n w JPanelO sultreegt enew this getContentPaneQ addtpane 2 l l GUltreeor JButton buttonl new JButton allte abound l JButton button2 new JButtor l Mallte a picture panelZaddtbuttbnzm tn leba39cm thlsrseLVlSlblelLrllex public GUltree superquotGU Tree Examplequot Whole I Put in a anel with a label in it I GUITree quot JPanel pane1 newJPanel JLabel label new JLabelquotThis is panel 1quot pane1addabel quotPut in another panel with two buttons in it JPanel panel2 new JPanel thisgetContentPaneaddpanel2 JButtonl button1 new JButtonquotMake a soun panel2addbutton1 JButtonl button2 new JB uttonquotM39ake a pl ure panel2addbutton2 thispack0 thissetVisibetrue Where d panel1 go It s there but the current rendering is smashing it all together GUItree is a tree JFrame J Panel J Panel n n JButton Make JButton JLabel This Is panel1 a soundquot picturequot Layout Managers are renderers How are the components assigned a position and size setLayoutnull the programmer must give all components a size and position 39 setBoundstopLeftXtopLeftYwidthheight Better Use a Layout Manager 39 Arranges the components in a container and sets their size as well 39 Handles when the main window is resized 39 The programmerjust adds the components to the container in itnto demonstrate layout managers rendering M Auuiiiiaiiia 39 Ul compbnentsiand eel F import javaxswing ll39Need thisito reach Swing cbmponents G u import javaawt ll Need this to reach FlowLayout publici class GU ltreeFIOWed e xtends JFramel public GU ltreeFIOWed superquotGU Tree Flowed Examplequot free new tiuiiipie 39 avniittriew FIowL39ayoutO P Put in a panel with a label in it JPan el panel1 new Panel thisgetContentPaneaddpanel1 JLabel label new JLabelquotThis is panel 1quot panel391addlabel gtquotGUItreeFlowed gtf new GUItreeFloWe d F Put Inanother panel With two buttons tn It I JPan el panel2 newJPanel thisgetContentPaneaddpanel2 JB utton button1 new JButtonquotMake a sdund panel2addbutton1 JB utton button2 new JButtonquotMake a picturequot P panel2addbuttoii2 tl139ispack thissetVisibletme t A GUl that nas various components in lt to demonstrate Ul components ano layou trna n39agers rendering W Bordered GUltree importiavax swtngy Need this to reach SWing components importiayaawt a weed tnis to reach Bordertayout poor ie39 JFram LII Tree Bordered ample El puoiio GUitreeBoroere o gr mmmm 1 superI GUl Tree Bordered Exam ple Make 2i siiunu Make 2 picture tnis getcon tentpanet setLayoutnew B oroerLayouw inapanetwtn eiaoeiinit t JPanelpanell newupaneig Lnrs39g etConte nLD a netaoo paneimBoroerL JLabel label new Laoeitrrn isisoaneit gt GUJtreeBordered gt paneit ad ot iao ei 39 39 new UltgreVeBorderedOr s w n Put in another panel Witn twp buttonS in it v JPanelpanelZ e39youtuoRTHt l BorderLayoptSOUTH on on soundi39li parieizaodmuttorit JButton utton2 new JButton Make a picture paneiiaoomutt onZ tnis packO thissetVisible rue l l Layouts Flow Border Grid Flow Layout left to right no extra space Buttunl A Euttuni LDngNamEdEuttunA Euttun Border Layout Center item gets extra space Nurth west East Suuth Grid Layout same size components Euttun 5 39 Euttun t y 2 l Euttun a K Automatical y reflows when resized eiii rree rim more Egg riiis IS panel 1 Make 2i siiunu Make 2 picture Resi ing now follows borders e GUI Tree Bordered Bample me Is panel 1 Make 2i siiunu l Make 2 picture Other Layouts None GridBag Card None null programmer specified Button 2 Button 3 Button 4 GridBag flexible grid Card one card shown at a time v Panel um Tatme v Buttunt Button 2 Button a banned Horizontal BoxLayoutXAXlS Vertical BoxLayoutYAXlS space between components BoxcreateRigidAreanew Dimension05 up extra space BoxcreateHorizontalGlue K BoxLayout WE Two types l Buttquot l l Butmn s l Can use rigidAreas to leave a set amount of Can use horizontal andor vertical glue to take I A GUI that has variouscomponents in it toudemonstrate UI components and layout managers rendering w Boxed 1 w GUItree public class GUltreeBoxed extends JFrame superC39GUl Tree Boxed EXample39f ithisgetContentPane0s etLayoutnew BoxLayoutthisgetContentPane1 B oxLayoutYAXlS I Put in a panel with a label in it I 39 JPanel panel1 new anel thisgetContentPane0addpanel1 JLabel label new J L abelquotThis ispanel 1quot panel1 addlabel BoxLayoutis weird it takesthe paneas an input and whether you want vertical or horizontal Y39or XAXI s boxing Put inanother panel with two buttons in it l d Panel panel2 new J Paneli thisgetContentPane0addpanel2 JButton button1 new JButtonquotMakeVaAsoundquot panel2addbutton1 JButton buttonZ new JButtonquotMake a picturequot pane2addbutton2 thispack0 thisset sibetrue gt KDiffers in resizing behavior It s all in boxes not borders GUI Tree Boxed Example This IS must 1 5 Jul Tree Boxed Example ElElE this is nansl ll l Make a snund l Make a quotinure Which Layout to Use K An applet or application can have multiple panels JPanel and have a different layout in each panel Panels can be inside of other panels If you want components to not use extra space and stay centered then use FlowLayout Or use BorderLayout and put one component that uses all extra space in the center Use a Box and line up components vertically or horizontally For he most control use null layout Much like LayeredSceneElement Nested Panel Example Often an application uses a BorderLayout Main panel in Center Other panels in North South West and East as needed 39 Using FlowLayout or Box In the application at right The main panel is in the center The button panel is in the 7 if 7 We y fill 39 Using FlowLayout K An Cavalcade of Swing Components Next few slides show you some of the many user interface components Swing in You don t have to know all ofthese They re here for your benefit Wait a few slides and we ll go through how to use basic buttons and text Swing JScrollPane JScrollPane adds scroll bars to component textArea new JTextArea5 30 JScrollPane scrollPane new JScrollPanetextArea contentPaneaddscrollPane BorderLayoutCENTER Swing Special Purpose Containers JTabbedPane display contents of current tab JToolBar groups buttons with icons JOptionPane display dialog box mannyasm JlnternalFrame inside frames Elle omlnns Cum 5mman Izhlewew DehuuGrzrhics Swing Bl K Swing Text Components k JLabel not editable text andor image EC Label 5 JLabeI firstNameLabel new JLabeI Labe 5 dukecon JTextField one line text entry andor display JTextFieId nameFieId new JTextFieId40 String name nameFieIdgetText leaniamin Franklin JPasswordField hides typed characters JPasswordField passField new JPasswordField8 passwnrmiw String password passFieldgetPasswordO JTextArea mul iline text entry andor display JTextArea commentArea new JTextArea230 WWWERM cabieiscunnecled String comment commentAreagetTextO iuiiewkw gimn on 2 I uni Swing List Components JList displays a list of items and user select one or more Color colors Black Blue Green JList colorList new JListcoIors colorList setVisibleRowCount2 String color colorListgetSelectedValueO may i Cuia JComboBox drop down list with selected displayed can set up for text entry too JComboBox colorBogtlt new JComboBogtltcoo String currColor colorBogtltgetSelected tem January isquot rList Swing Slider and Progress Bar JSlider show a value in a range or pick a value from a continuous range 5 new JSIider100 1000 400 ssetPaintTickstrue ssetMajorTickSpacing100 sgetValue get the current value from a slider 0 JProgressBar used to show how long a user needs to wait yet progressBar new JProgressBarJProgressBarHORlZONTAL 0 tegtlttlength E Color Chooser JCoIorChooser use to pick a color Use the static method showDialog and pass it the parent component title and current color Color newColor JCoIorChooser showDialog parentComponent title selCoor Example Color newColor JCoIorChooser showDialog this Pick a new background colorquotthisgetBackground i l39 l l File Chooser JFiIeChooser use to pick a le create the file chooser final JFiIeChooser fc new JFiIeChooser display the chooser as a dialog and get the return value int returnVal fcshowOpenDialogframe ifthe return value shows that the user selected a file if returnVal JFiIeChooserAPPRVOVEr OPTION 7 V 7 File file fcgetSelectedFile lEE E 239 Key to Interactive User Interfaces Events An event is an object that represents an action user clicks the mouse user presses a key on the keyboard user closes a window In Swing objects add or implement listeners for events Listeners are interfaces Interfaces are not classes They define functionality that other classes implement K It s a contract that certain functionality will be provided Events and Listeners K Say you want to know when your favorite band will be giving a tour in your city You might signup to be notified and give your e mail address Your name and email is added to a list When the event is scheduled in your city You will be notified via e mail that the tour is coming Events and Listeners Adapters K An adapter is an abstract class that provides empty implementations for a listener interface You can inherit from an adapter and only override the methods you want to handle class MyMouseAdapter extends MouseAdapter Method to handle the click of a mouse public void mouseClickedMouseEvent e Named Inner classes m 3an you can use mnercasses wnmn are masses dec ared mswde andmer mass pom mass C assName allnbules simmers mamas mass MyMouseAdaDler extends MouseAdaDler mamas Anonymous Inner classes You can Create a new llstener In place wun an anonymous Inner Class n addFucusLxstene nexv FocusLxstenEr pubhc vmd focusGamed FocusEvem eve mum vmd focusLuStFucusEvem eve n Interactive GUItree Starting out M mongol n men Interactive GUItree First button 39Pm n anmnerpanewmm hunhnsm w Jpane pane ge newJPaneK 5 e ex p heweaampemmeaowmzvmen m 5 neweounmecneosegemmmwhen We 37 am 39 pane 2 mommy Interactive GUItre Second button unhullonz newJBullONMalgap uwe mm addAman eHeK n Hee Heresmemmhodmreovemdmg Dubhc vmd anmnyenmeawmzvem an 7 murev newmurampFeChoosef gexMemaValh snaps panw genome An We use h m meme vanesmung use we use on no men h sswh w manesm Ema Example A Rhythm Constructing Tool Take a name of a sound to add to a root Building the RhythmTool class Starting the Wlndow J Frame Number fl39eld r a w Mu glam wan 4 m 3E n 1 v yummy mm mil r Recitation Guide Wednesday July 18 1 House Keeping a Exam 2 i Comments b Extra Credit Homework 9 i htt cowebcc atechedu cs1316 633hw9 An individual assignment with limited help from TAs f greater than lowest homework score then it will replace the lowest homework score c Extra Optional Quiz 39 July 23 and July 25 during recitation f grade is higher than lowest quiz grade then this grade replaces lowest quiz grade iquot Topics likely to be highly comprehensive d Final Exam i Held Wednesday 250pm e Homework 8 i htt cowebcc atechedu cs1316 633hw8 Due Wednesday July 17 1145pm with grace until Thursday July 18 700am Cannot be pushed back more iv Feel free to tweak some of the numbers in red to see if you can get better results 2 DES Discrete Event Simulations a Remember that i In discrete simulations not every moment in time is simulated ii Queues are FIFO First in First out structures b The EventQueue i Because there is no time loop time events need to be placed in the EventQueue where the first one removed processed is the event that occurs the earliest in time At each run step the next scheduled event with the lowest time gets processed The current time is then that time the time that that event is supposed to occur c Agents In a discrete event simulations agents do not act Instead the agents wait for events to occur and schedule new events to correspond to the next thing that they are going to do Events also get scheduled according to different probabilities resources An agent is blocked until more resource is available d Uniform distributions versus normal distributions i Normal distribution Gaussian or the bell curve However agents cannot always do what they want to do because of limited O D cunt II I II II PPM 9 moom 5 4 3 2 1 0 l 2 3 4 5 Uniform distribution 0 39 bia e Insertion Sort i How it works 1 The insertion sort algorithm sorts a list of values by repetitively inserting a particular value into a subset of the list that has already been sorted One at a time each unsorted element is inserted at the appropriate position in that sorted subset until the entire list is in order Each time an insertion is made the number of values in the sorted subset increases by one The insertion process requires that the other values in the array shift to make room for the inserted element ii Needed to insert new events into the EventQueue in the correct order iii Big o 1 Best case n for an already sorted list 2 Worst case n2 fora list sorted in reverse order iv Example 92135104786where sortedlist unsorted list 1 92135104786 29135104786 12935104786 12395104786 12359104786 12359104786 12345910786 12345791086 12345789106 10 12345678910 v Othersorts 5 P N9P1P9 N 1 Bubble sort selection sort insertion sort radix sort heap sort quick sort merge sort 2 Only responsible for insertion sort in this course 3 Homework 8 questions Issues Traversing the Linked List Dam Hme 31316 Traversing the Linked List Question Suppose we have a linked list of books in a library and the books are defined as follows public class BookElement private String bookDetails private BookElement next null nu I public String getDetails return thisbookDetails public BookElement getNext return thisnext39 public void setDetailsString details thisbookDetails details public void setNextBookElement be thisnext be Write a method length that returns the length of the list that starts at this by filling in the code template 1316 Traversing the Linked List Code Template public int length Hint Initialize number here You also need a current element starting at this Hint Then comes the while loop for the traversal while Hint do something inside the loop that helps you count Hint do something so that the loop does not repeat forever return number 1316 Traversing the Linked List Provided Solution public int length Hint Initialize number here int number 1 You need a current element starting at this BookElement current this Hint Then comes the while loop for the traversal while currentgetNext null Hint do something inside the loop that helps you count number Hint do something so that the loop does not repeat forever current currentgetNext return number 1316 Traversing the Linked List Testing the Solution Setting up the Test List BookElement nodel new BookElement BookElement node2 new BookElement BookElement node3 new BookElement node1setNextnode2 node2setNextnode3 node 1 node 2 node 3 null Systemoutprintlnnode1ength CSl316 Traversing the Linked List Testing the Solution Running through the Method public int lenglh int numbe 7 BookElemenl current this while currenlgelNext null nulnber culrenl curlenlgelNegtltl ode 1 return numbel number 1 Now we have a variable numberthat will act as our counter and we initializelvit tp 1 55131 Travarslngthe mm Llst Testing the Solution Running through the Method public int ength int number 7 current 1 BookElemenl current this while currenlgelNexl null nulnber culrenl cunentgetNext return number number 1 Now we have a variable current acting as a pointer to the current node we ere considering inytheIist 55131 Treversmgthe Linked List Testing the Solution Running through the Method public int length int numb r 1 BookElement current r is while currentgelNexl null nulnber culrent curlenlgelNegtltt return numbel Because the expression currentgetNext null evaluates to true w enter therloopu current number 1 551m Treverslrlgthe Llrrked Llst Testing the Solution Running through the Method public int englh int num 1 current BookElement current this while currentgelNexl null number culrenl curlenlgelNegtltl return numbel number 2 Add 1 to numbe 551316 Traversmgthe errkeu L151 Testing the Solution Running through the Method public int lenglh int nllm e 1 current BookElemenl current this while currenlgelNexl null nulnb er current currenlgelNegtltl ode 1 return numbel number 2 We have finished looking at the current so change it toithe next node 551m Treverslrlgthe Llnked m Testing the Solution Running through the Method public int length int numb 1 BookElement current this while currentgelNext null nulnber Culrenl curlenlgelNegtltt return numbel number 2 Because the expression currentgetNext null evaluates to true the loop continues 551m Treverslrlgthe Llrrked Llst current 1 Testing the Solution Running through the Method public int lenglh inlnllm 71 current BookElemenl current this while currenlgelNexl null nu b m er Culrenl curlenlgelNegtltl ode 1 return numbel number 3 Add 1 to numbe 551316 TravErslrlgthE LlnkEd Llsl Testing the Solution Running through the Method public int englh int num 1 BookElemenl current this while currenlgelNexl null nulnber current currentgetNext ode 1 return numbel number 3 We have finished looking at the current so change it toithe next node CSial Trevarsmgthe Lmked ust Testing the Solution Running through the Method public int lenglh int numb 1 BookElemenl current this while currenlgelNexl null nulnber culrenl curlenlgelNegtltl ode 1 return numbel number 3 Because the expression currentgetNext null evaluates to false we do th enter theIczoplagain 551m Treverslrlgthe Llnked Llst Testing the Solution Running through the Method public int lenglh int nllm e 1 BookElemenl current this while currenlgelNexl null nulnber culrenl curlenlgelNegtltl ode 1 return number number 3 Return the number we have calculate 551m Treverslrlgthe Llnked Llst Flaws within the Solution It is okay to presume that number starts at 1 because we know that we have at least 1 node in the list We know that there is at least 1 node in the list because we are within the method so we know that this is not null or we would have received a NullPointerException and gotten kicked out before we even entered the method However with the presumption that the number starts at 1 we cannot have current set to this because we have already counted this by starting at 1 The current node should start at thisgetNext Regardless of whether number starts at O or 1 current starts at this or thisgetNext the while conditional should be current null so that we will actually visit each node C81316 Traversing the Linked List Better Solution public int length Hint Initialize number here int number 0 You need a current element starting at this BookElement current this Hint Then comes the while loop for the traversal while current null Hint do something inside the loop that helps you count number Hint do something so that the loop does not repeat forever current currentgetNext return number 1316 Traversing the Linked List Testing the Better Solution Setting up the Test List BookElement nodel new BookElement BookElement node2 new BookElement BookElement node3 new BookElement node1setNextnode2 node2setNextnode3 node 1 node 2 node 3 null Systemoutprintlnnode1getLength CSl316 Traversing the Linked List Testing the Solution Running through the Method public int lenglh int num e BookElemenl current this while current null nulnber culrent cunentgetNext return numbel number 0 Now we have a variable numberthat will act as our counter and we initializehit tp 03 CSial Treverslrlgthe Llnked Llsl Testing the Solution Running through the Method public int ength int numb current 0 BookElement current this while current null number culrenl cunentgetNext return numbel number 0 Just like before we have a variable current acting as a pointer to the current ode we are considering in the list 551m Treversmgthe Linked List Testing the Solution Running through the Method public int length int nllmbe o BookElement current this while current null nulnber culrent cunentgetNext return numbel Because the expression current null evaluates totrue we enter the loop current number 0 Csial Treverslrlgthe Llrrked Llsl Testing the Solution Running through the Method public int lenglh int nllm r 0 BookElemenl current this while current null number culrent cunentgetNext return numbel Add 1 to numbe current 1 number 1 551316 TravErslrlgthE LlnkEd Llsl Testing the Solution Running through the Method public int lenglh int nllm e 0 current BookElemenl current this while current null nulnb er current currentgetNext ode 1 return numbel number 1 We have finished looking at the current so change it toithe next node CSial Trevarslrlgthe Llrrked Llsl Testing the Solution Running through the Method public int ength int numb current o BookElement current this while current null nulnber culrenl cunentgetNext ode 1 return numbel number 1 Because the expression current null evaluates to true the loop continues 551m Treversmgthe Linked List Testing the Solution Running through the Method public int lenglh intnum 70 current BookElemenl current this while current null nu b m er culrent cunentgetNext ode 1 return numbel number 2 Add 1 to numbe 551316 TravErslrlgthE LlnkEd Llsl Testing the Solution Running through the Method public int lenglh int nllm e 0 BookElemenl current this while current null nulnber current currentgetNext ode 1 return numbel number 2 We have finished looking at the current so change it toithe next node CSial Trevarslrlgthe Llrrked Llsl Testing the Solution Running through the Method public int ength int numb o BookElemenl current this while current null nulnber culrenl cunentgetNext ode 1 return numbel number 2 Because the expression current null evaluates to true the loop cpntinues CSial Treversingthe Linked List Testing the Solution Running through the Method public int lenglh int nllm r 0 BookElemenl current this while current null number culrent cunentgetNext ode 1 return numbel number 3 Add 1 to numbe 551316 TravErslrlgthE LlnkEd Llsl Testing the Solution Running through the Method public int lenglh int nllm e 0 BookElement current this while current null nulnber current currentgetNext return numbel We have finished looking at the current so change it toithe next node current number 3 CSial Treverslrlgthe Llrrked Llsl Testing the Solution Running through the Method public int length int nllmbe 0 BookElement current this while current null nulnber culrent cunentgetNext return numbel Because the expression current null evaluates to false the loop ends current number 3 Csial Treverslrlgthe Llrrked Llsl Testing the Solution Running through the Method public int lenglh int nllm e 0 Current BookElemenl current this while current null nulnber culrent cunentgetNext ode l ode 3 null return number number 3 Return the number we have calculate CSial Treverslrlgthe Llrrked Llsl S to ry Discrete Event Simulation Discrete event simulation Simulation time i realtime Key ideas A Queue A ue is a queue no matter how implemented Dirrerent kinds or random straigntenin tirne nserting it into tne rignt place Sorting it arterwards Building a discrete event simula io crapnies as tne representation not tne real tning Tne Model and tne View 081316 Representing Structure and Behavior Finally A Discrete Event Simulation Running a DESimuIation Now we can assemble queues different Welcome to DrJaVa kinds of random and a sorted gt FaOtOrysrmuration f5 new EventQueue to create a discrete event Factorysmuiatbno S39mUIat39on39 gt fs iopenFrames quotDtempquot gt fsrun250 The detal tells the story mm Time Time Wm ime Time gtgtgt 71m 71m Time 1 7173517133337525 0151mm n 1 7n7aao71a33a7525 015171an I meae p 1 1727155311113511 Dishibulur Anivedatwavehuuse 1 727155311113511 015171an7 3 1531mm mm 1 1 a77375w13nn1u3 015171an7 6 Arrivedatvvaiehuuse 1 3773751313 1m Dis1 ibulur i isblucklng mm n1 1333175man31eag Dishibulur i ga m nai 39aa 0151mm 2 2 2p 3neiaeu37a1aza33 0151mm Amvedatwavehuuse anm euax lazaaa 0151mm 1331mm 8123 3 NZUSNWUZEB Truck 2 Arrived at wavehnuse with luau 366662U37657U2 3 0151mm 1 linblubkedi liozn37ia7nzaa Dislvinuurn Gal mudug uv 251271 V 39 V 3 aaaaeawzzmzeamw n V Arrived atwavehnusewithluad 3 3353537322332533 015171an7 3 unbluckedi 388596579228326981 Dishibulm39 3 512773 m2 Anivedalwavehuuse isblucklng Gatheredgmductimpvdevspi 12 What questlons we can answer How long do distributors wait Subtract the time that hey unblock 39om the time that they block How much roduct sits in the warehouse At each time a distributor leaves gure out how much is lelt in the warehouse How long does the line get at the warehouse At each block count the size ofthe queue ore product by having more distributors or more trucks Try it How DESimulatIon works FactoryS39mulation Extend a few classes DESimulation Sets the Stage DESimulation calls setUp to create agents and schedule the first events It provides log for writing things out to the console and a text file When it run s it processes each event in the event queue and tells the corresponding agent to process a particular message What a DESimulation does While we re neiyeiaiihe siepiime Hand there are mu evenisie pincess W re hile nuw lt39 stupTlmE mieveme empiyom tupEventZEvems pupa lVvh teverev392 nl is quotattentive is nuw AS mg as were are nuwrt m gemm39 L2Hh2 ag em nuw that its evem has Declined We in Weller lepAgentiepEvemgeiAgemo a dwerenotatthe n tupAgent prucessEve lepEvem getMes sage D 51de lrepainllhewurld in shuwlhe muvemenl Iiirmeye lsa WWW walla l null wurld repainto Process the event Noellie elm distep pincessing imseneSiepmm new i What s an Event SimEvent L SimulatiunEve nt SimEvEnt i an e veni m ai ucciJrs in a siyn uiaimn iikee imek ahwmgfai gramme 2 sales39peree n leaving me is a We an film A ent an n d publicclassSimEventl lntegerthatthe iFi2lds gehtWill f r rWhEnduesthisevemuccuy7 understand as a public deubienme megg39a g e we whum dues it uccur Vlhu emu be quotrimmed when39ituccuned publicDEAgent mum hwwaiis h enh e e t e m2 we ll use mge g eiquotnrepvesemmemeamng vanlr meimessage mime Event Eachag ntwill kn39uwthe meaning eime imegerreyihemeeives pueiiemi39message DEAgent Process events block if needed DEAgents de ne the constants for messages What will be the main events for this agent If the agent needs a resource it asks to see if it s available and if not it blocks itself It will be told to unblock when it s ready Agents are responsible for scheduling their OWN next event An Example A Truck How Trucks start tripTime uses the normal distribution newLoad uses uniform How a Truck processes Events Truck Arriving at the Warehouse What Resources do How Resources alert agents They keep track of what amount they have available ofwhatever the resource is They keep a queue of agents that are blocked on this resource They can add to the resource or have it consumed 39 When more resource comes in the head ofthe queue gets asked if it s enough lfso it can unblock An example blocking agent Distributor Distributors start in the Market Distributors have 3 events Arrive in Market Schedule how long it ll take to deliver Leave Market Schedule arrive at the Factory 39 Arrive at Warehouse Is there enough product available If not block and wait for trucks to bring enough product Processing Distributor Events Leaving the Market Arriving at the Warehouse Is there enough product If so we ll be unblocked