Java Reference
In-Depth Information
As a general rule, you keep all statements to be executed only once in the init method.
The paint method is used to draw various items, including strings, in the content pane
of the applet. Thus, in the applets presented in this chapter, we use init to:
￿ Initialize variables
￿ Get data from the user
￿ Place various GUI components
The paint method is used to create the output. The init and paint methods need to
share common data items, so these items are the data members of the applet.
Let's now create an applet that will display a welcome message. Because no initialization
is required, all you need to do is override the method paint so that it draws the welcome
message. Sometimes when you override a method, it is a good idea to invoke the
corresponding method of the parent class . Whenever you override the paint method,
the first Java statement is:
super .paint(g);
where g is a Graphics object. Recall that super is a reserved word in Java and refers to
the instance of the parent class.
To display the string containing the welcome message, we use the method drawString
of the class Graphics . The method drawString is an overloaded method. One of the
headings of the method drawString is:
public abstract void drawString(String str, int x, int y)
The method drawString displays the string specified by str at the horizontal position
x pixels away from the upper-left corner of the applet, and the vertical position
y pixels away from the upper-left corner of the applet. In other words, the applet
has an x-y coordinate system, with x ¼ 0 , y ¼ 0 at the upper-left corner; the x value
increases from left to right and the y value increases from top to bottom. Thus, the method
drawString , as given previously, draws the string str starting at the position (x, y) .
The following Java applet displays a welcome message:
1
2
//Welcome Applet
import java.awt.Graphics;
import javax.swing.JApplet;
public class WelcomeApplet extends JApplet
{
public void paint(Graphics g)
{
super .paint(g);
//Line 1
g.drawString("Welcome to Java Programming",
30, 30);
//Line 2
}
}
Search WWH ::




Custom Search