Java Reference
In-Depth Information
115 repaint();
116 }
117
118 /** Move the message up */
119 public void moveUp() {
120 yCoordinate -= interval;
121 repaint();
122 }
123
124 /** Move the message down */
125 public void moveDown() {
126 yCoordinate += interval;
127 repaint();
128 }
129
130 @Override /** Override get method for preferredSize */
131
override
getPreferredSize
public Dimension getPreferredSize() {
132
return new Dimension( 200 , 30 );
133 }
134 }
The paintComponent method displays the message centered, if the centered property
is true (line 91). message is initialized to Welcome to Java in line 8. If it were not
initialized, a NullPointerException runtime error would occur when you created
a MessagePanel using the no-arg constructor, because message would be null in
line 103.
Caution
The MessagePanel class uses the properties xCoordinate and yCoordinate to
specify the position of the message displayed on the panel. Do not use the property
names x and y , because they are already defined in the Component class to return the
position of the component in the parent's coordinate system using getX() and
getY() .
Note
The Component class has the setBackground , setForeground , and setFont
methods. These methods are for setting colors and fonts for the entire component. If
you wanted to draw several messages in a panel with different colors and fonts, you
would have to use the setColor and setFont methods in the Graphics class to
set the color and font for the current drawing.
Note
A key feature of Java programming is the reuse of classes. Throughout this topic,
reusable classes are developed and later reused. MessagePanel is an example, as are
Loan in Listing 10.2 and FigurePanel in Listing 13.3. MessagePanel can be
reused whenever you need to display a message on a panel. To make your class reusable
in a wide range of applications, you should provide a variety of ways to use it.
MessagePanel provides many properties and methods that will be used in several
examples in the topic.
design classes for reuse
13.21 If message is not initialized in line 8 in Listing 13.8, MessagePanel.java, what will
happen when you create a MessagePanel using its no-arg constructor?
13.22 The following program is supposed to display a message on a panel, but nothing is
displayed. There are problems in lines 2 and 15. Correct them.
Check
Point
 
Search WWH ::




Custom Search