Java Reference
In-Depth Information
Self-Test Exercises
7. What kind of event is fired when you click a JButton ?
8. What method heading must be implemented in a class that implements the
ActionListener interface?
9. Change the program in Display 17.2 so that the window displayed has the title
"My First Window" . Hint : Consult the description of constructors in Display 17.3 .
EXAMPLE: A Better Version of Our First Swing GUI
Display 17.4 is a rewriting of the demonstration program in Display 17.2 that
includes a few added features. This new version produces a window that is similar to
the one produced by the program in Display 17.2. However, this new version is done
in the style you should follow in writing your own GUIs. Notice that the window is
produced by defining a class (FirstWindow) whose objects are windows of the kind
we want. The window is then displayed by a program (DemoWindow) that uses the
class FirstWindow .
Observe that FirstWindow is a derived class of the class JFrame . This is the
normal way to define a windowing interface. The base class JFrame gives some basic
window facilities, and then the derived class adds whatever additional features you
want in your window interface.
Note that the constructor in Display 17.4 starts by calling the constructor for the
parent class JFrame with the line
super ();
As we noted in Chapter 7 , this ensures that any initialization that is normally done
for all objects of type JFrame will in fact be done. If the base class constructor you
call has no arguments, then it will be called automatically, so we could have omitted
the invocation of super() in Display 17.4. However, if the base class constructor
needs an argument, as it may in some other situations, then you must include a call to
the base class constructor, super .
Note that almost all the initializing for the window FirstWindow in Display 17.4 is
placed in the constructor for the class. That is as it should be. The initialization, such
as setting the initial window size, should be part of the class definition and not actions
performed by objects of the class (as they were in Display 17.2). All the initializing
methods, such as setSiz e and setDefaultCloseOperation , are inherited from the
class JFrame . Because they are invoked in the constructor for the window, the window
itself is the calling object. In other words, a method invocation such as
setSize(WIDTH, HEIGHT);
is equivalent to
this .setSize(WIDTH, HEIGHT);
(continued)
 
Search WWH ::




Custom Search