Placing Text on an Applet
Let's spend some more time with text in Java. To create the applet below, we create a subclass of Font called f and define it to be TimesRoman, Bold and 36 points. By creating an instance or object, g of this new subclass we can set the font and color of g.
The applet shown below draws the string in a 301x301 window.
The code for this Java line applet is listed below.
import java.awt.Graphics;
import java.awt.Font;
import java.awt.Color;
public class Hellothe extends
java.applet.Applet {
Font f = new Font("TimesRoman",
Font.BOLD, 36);
public void paint (Graphics g) {
g.setFont(f);
g.setColor(Color.green);
g.drawString("Hello there!",
50, 100);
}
}
|
This allows us
to use the Graphics methods of the Java Abstract
Windowing toolkit. We want to generate an applet . A subclass of Font, f, is declared with the attributes enclosed in the parentheses. The paint method is the way an applet draws objects on the screen. g is an instance of the Font subclass f. g is also set to green The method drawstring is used to draw "Hello There" in the defined window. The bottom left corner of the string is located at the coordinate (50,100) |
The applet shown below draws the string in a 100x200 window. When the designated window is too small for the applet, it is clipped.
The string can easily be changed to red, italic, and 48 points.
After compiling this program we need to create an HTML page with a reference to the class file. It must run in a graphic window that is large enough to accomodate the pixels in the applet.
Save the HTML code in the same directory as the class file.
When you load the HTML file in your browser the applet will execute within the window.
Go to the next topic: Lines