A fancier drawing program |
For the next example, we go back to the drawing program that we first used as an example of using GUI components. It has choice buttons to determine the shape of the object to be drawn (square or circle) and its color. Now we would like to enhance the program to allow the user to click on one of the objects on the canvas and drag it to a new position. We do that by adding a new choice button that will allow us to choose whether we wish to draw a new geometric object, or select an old one to drag. The drawing is handled as before, but selecting an element used to be impossible because once we created a new object, the variable holding the old object now only refers to the new object, leaving the old object inaccessible. We will now make up for that by keeping all of the entries on the screen in an array.
Notice the code to create a new array does not create any items in the array. That is handled by the call of addNew in onMousePress.
We bump up the count of the number of objects after each addition of a new element. Thus numObjects provides an accurate count of the number of objects of the array which are really in use. The constant maxArray simply keeps track of the total number of available slots, not the number of slots in use.
Notice also that the first statement of the addNew method checks to make sure that numObjects is less than maxObjects. If we omitted that check and tried to insert something in geomObject[maxObjects] we would get an ArrayIndexOutOfBoundsException and your program would crash.
A fancier drawing program |