Sub-classing AWT classes
A simple way
to allow additional functionality to be added to basic AWT classes. There are
limitations to the user interface elements that can be created this way.
The easiest
way to create a new user interface element is to define a subclass of an AWT
class that is similar.
For example,
you could create a class called RedButton
which was identical to the standard Button
class except for having a red background (the default is grey). The code for
this might look like:
public class RedButton extends Button
{
public RedButton (String label)
{
super
(label);
setBackground(Color.red);
}
}
But we could
not use this method to create, say, a round button, or a button that pops up a
message when the mouse moves over it. Why not? Class Button is an abstraction of the 'real' button that appears on the display.
It only offers functionality that is common to all or most real computer
systems. Few real graphical user interfaces allow circular buttons to be
created automatically, so class Button cannot provide this. This is a necessary
price to pay for portability, but it can be very frustrating.
So how could
you create a circular button? Probably the easiest way is to create a subclass
of a different AWT element. A good candidate here would be Canvas. A Canvas object is simply a blank,
rectangular region of the screen. Your program would have to draw the button as
it would appear, and take appropriate action when the user clicks on it. This
is significantly more complex than subclassing Button.
Look back to
the Button1.java
applet - perhaps try changing it to use the RedButton class above.
|