Java Reference
In-Depth Information
Self-Test Exercises (continued)
22. You are used to defining derived classes of the Swing class JFrame . You can also
define derived classes of other Swing classes. Define a derived class of the class
JPanel that is called PinkJPanel . An object of the class PinkJPanel can be used
just as we used objects of the class JPanel , but an object of the class PinkJPanel
is pink in color (unless you explicitly change its color). The class PinkJPanel will
have only one constructor, namely the no-argument constructor. ( Hint: This is
very easy.)
TIP: Code a GUI's Look and Actions Separately
You can divide the task of designing a Swing GUI into two main subtasks: (1) Design-
ing and coding the appearance of the GUI on the screen; (2) Designing and coding
the actions performed in response to button clicks and other user actions. This divid-
ing of one big task into two simpler tasks makes the big task easier and less error
prone.
For example, consider the program in Display 17.11. Your first version of this pro-
gram might use the following definition of the method actionPerformed :
public void actionPerformed(ActionEvent e)
{}
This version of the method actionPerformed does nothing, but your program will run
and will display a window on the screen, just as shown in Display 17.11. If you click any
of the buttons, nothing will happen, but you can use this version of your GUI to adjust
details, such as the order and location of buttons.
After you get the GUI to look the way you want it to look, you can define the
action parts of the GUI, typically the method actionPerformed .
If you include the phrase implements ActionListener at the start of your JFrame
definition, then you must include some definition of the method actionPerformed . A
method definition, such as
public void actionPerformed(ActionEvent e)
{}
which does nothing (or does very little) is called a stub . Using stubs is a good program-
ming technique in many contexts, not just in Swing programs.
Alternatively, when writing your first version of a Swing GUI like the one in Dis-
play 17.11, you could omit the definition of the method actionPerformed completely,
provided you also omit the phrase implements ActionListener and omit the invocations
of addActionListener .
stub
Search WWH ::




Custom Search