adhitz

counter

hit counter

on

adhitz

Monday, May 16, 2011

A Sample Applet


This hour's first project is an applet that displays the string "Saluton mondo!", the traditional Esperanto greeting that is becoming more traditional by the hour. You'll take a look at how applets are structured by re-creating the Saluton application from Hour 2, "Writing Your First Program," as a program that can run on a web page.
Load your word processor and create a new file called SalutonApplet.java. Enter the text of Listing 17.1 into the file and save it when you're done.

Listing 17.1. The Full Text of SalutonApplet.java

1: import java.awt.*;

 2:

 3: public class SalutonApplet extends javax.swing.JApplet {

 4:     String greeting;

 5:

 6:     public void init() {

 7:         greeting = "Saluton mondo!";

 8:     }

 9:

10:     public void paint(Graphics screen) {

11:         Graphics2D screen2D = (Graphics2D)screen;

12:         screen2D.drawString(greeting, 25, 50);

13:     }

14: }


This applet does not need to use the start(), stop(), or destroy() methods, so they are not included in the program. Compile the program with the javac compiler tool, if you're an JDK user, or another tool.

Drawing in An Applet Window

Text is displayed in an applet window by using the drawString() method of the Graphics2D class, which draws text in a graphical user interface component.
The drawString() method is similar in function to the System.out.println() method that displays information to the system's standard output device.
Before you can use the drawString() method, you must have a Graphics or Graphics2D object that represents the applet window.
The paint() method of all applets includes a Graphics object as its only argument, which can be cast to a Graphics2D object:
Graphics2D screen2D = (Graphics2D)screen;


When you have created a Graphics2D object like this, you can call its drawString() method to display text on the area represented by the object.
The following three arguments are sent to drawString():
  • The text to display, which can be several different strings and variables strung together with the + operator
  • The x position (in an (x,y) coordinate system) where the string should be displayed
  • The y position where the string should be displayed
The (x,y) coordinate system in an applet is used with several methods. It begins with the (0,0) point in the upper-left corner of the applet window. Figure 17.1 shows how the (x,y) coordinate system works in conjunction with the statement on Line 12 of SalutonApplet.java.

0 comments:

Post a Comment

Popular Posts

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Justin Bieber, Gold Price in India