Exercise 4: Creating Classes

CS 116

Sept. 18, 2002

  1. Take a look at the file Lesson4.java from the web page. Create a Lesson4 project and try it out.

  2. Create a second MyPanel object in your applet which will appear on the right or ``east'' border of the applet.

  3. Change the MyPanel class so that the constructor takes 4 String arguments which specify the labels of the four buttons. Change the applet so that the buttons on the first panel are still labeled ``1'', ``2'', ``3'', ``4'' but the buttons on the second panel are labeled ``A'', ``B'', ``C'', ``D''. Notice that all that changes in your applet is how you call the constructor for MyPanel.

  4. Add another class called MyCanvas which extends the Canvas class. (A canvas is a container which has a paint method with which you can add graphics.) Your class should have a constructor function which simply sets the canvas background to yellow. Your class should also have a public paint method which draws a red circle somewhere on the canvas. Now in your applet, create a MyCanvas object and add the object to the center of the applet. (Look up how you add to the center with the BorderLayout.)

  5. Change MyCanvas so that the circle is always drawn in the center of the canvas (even when the canvas is resized!). To do this you need to determine the size of the canvas within the paint() method. The method getSize() returns a Dimension object indicating the size of the container.

    Look up the Dimension class in the documentation and see if you can figure out how to do this more challenging problem.



Thomas P. Kelliher
Mon Sep 16 09:58:25 EDT 2002
Tom Kelliher