Java Reference
In-Depth Information
18.14
What is wrong if the
DisplayMessage
applet is revised as follows?
public class
DisplayMessage
extends
JApplet {
/** Initialize the applet */
public
DisplayMessage() {
// Get parameter values from the HTML file
String message = getParameter(
"MESSAGE"
);
int
x =
Integer.parseInt(getParameter(
"X"
));
int
y =
Integer.parseInt(getParameter(
"Y"
));
public class
DisplayMessage
extends
JApplet {
private
String message;
private int
x;
private int
y;
@Override
/** Initialize the applet */
public void
init() {
// Get parameter values from the HTML file
message = getParameter(
"MESSAGE"
);
x = Integer.parseInt(getParameter(
"X"
));
y = Integer.parseInt(getParameter(
"Y"
));
// Create a message panel
MessagePanel messagePanel =
new
MessagePanel(message);
messagePanel.setXCoordinate(x);
messagePanel.setYCoordinate(y);
}
public
DisplayMessage() {
// Create a message panel
MessagePanel messagePanel =
new
MessagePanel(message);
messagePanel.setXCoordinate(x);
messagePanel.setYCoordinate(y);
// Add the message panel to the applet
add(messagePanel);
}
}
// Add the message panel to the applet
add(messagePanel);
}
}
(a) Revision 1
(b) Revision 2
This section presents an applet that displays a ball bouncing in a panel.
Key
Point
The applet uses two buttons to suspend and resume the bouncing movement, and uses a scroll
bar to control the bouncing speed, as shown in Figure 18.8.
F
IGURE
18.8
The ball's movement is controlled by the
Suspend
and
Resume
buttons and the
scroll bar.
Here are the major steps to write this program:
1. Define a subclass of
JPanel
named
Ball
to display a ball bouncing, as shown in
Listing 18.7.
2. Define a subclass of
JPanel
named
BallControl
to set the ball speed with a scroll
bar, and two control buttons
Suspend
and
Resume
, as shown in Listing 18.8.
3. Define an applet named
BounceBallApp
to contain an instance of
BallControl
and
enable the applet to run as a standalone application, as shown in Listing 18.9.
The relationship among these classes is shown in Figure 18.9.