Slightly Better Organized Basic GUI
Click on the buttons to alternate colors, and write in the textbox the
name of the desired shape.
Why is this program better than the previous one? Because it separates the part that controls what we want to do
(buttons, textfield) from the part that does the visualization (the canvas, which is a viewer).
This applet is a variation on the previous one, with a different organization of the Java code. It is your first program
that uses two separate classes to create a program:
- myApplet.java: the main applet, which handles the buttons.
- myCanvas.java: a new class, specifically designed for drawing shapes of different colors.
Notice the constructor method of the class. This contains code that is invoked each time you create a new
object of the type myCanvas. The constructor has the same name as the class for which it is intended.
The constructor may in general have parameters, but here we illustrate one without any parameters.
Read the code carefully and notice that the program separates the Canvas,
i.e. the part that handles the drawing,
from the applet initialization.
Notice that we create a new class myCanvas which extends the existing class Canvas. We need
to extend an existing class which can paint, and Canvas does it (check its documentation to convince yourselves that
it has this ability).