Applets are displayed in a window and they use the AWT to perform input and output functions. To output a string to an applet, use drawString( ), which is a member of the Graphics class. Typically, it is called from within either update() or paint( ). It has the following general form:
void drawString(String message, int x, int y)
Here, message is the string to be output beginning at x, y. In a Java window, the upper-left corner is location 0, 0. The drawString( ) method will not recognize newline characters. If we want to start a line of text on another line, we must do it manually, specifying the X,Y location where we want the line to begin.
To set the background color of an applet's window, we use setBackground( ). To set the foreground color, we use setForeground(). These methods are defined by Component, and have the general forms:
void setBackground(Color newColor)
void setForeground(Color newColor)
Here, newColor specifies the new color. The class Color defines the following values that can be used to specify colors:
Color.black Color.magenta Color.blue Color.orange Color.cyan Color.pink Color.darkGray Color. red Color.gray Color.white Color. green Color.yellow Color.lightGray
For example, this sets the background color to blue and the text color to yellow:
setBackground(Color.blue);
setForeground(Color.yellow);
We can change these colors as and when required during the execution of the applet. The default foreground color is black. The default background color is light gray. We can obtain the current settings for the background and foreground colors by calling getBackground( ) and getForeground( ), respectively. They are also defined by Component and bear the general form:
Color getBackground()
Color getForeground()
The example below shows a simple applet to change the color of the foreground and background.
import java.awt.*; import java.applet.*; /* <applet code="Applet_Prog" width=500 height=550> </applet>*/ public class Applet_Prog extends Applet { public void paint (Graphics g) { setBackground(Color.BLUE); setForeground(Color.RED); g.drawString("Using Colors in An Applet" , 100,250); } }
The output of the Applet would look like:
No comments:
Post a Comment