Scrigroup - Documente si articole

Username / Parola inexistente      

Home Documente Upload Resurse Alte limbi doc  

AccessAdobe photoshopAlgoritmiAutocadBaze de dateCC sharp
CalculatoareCorel drawDot netExcelFox proFrontpageHardware
HtmlInternetJavaLinuxMatlabMs dosPascal
PhpPower pointRetele calculatoareSqlTutorialsWebdesignWindows

AspAutocadCDot netExcelFox proHtmlJava
LinuxMathcadPhotoshopPhpSqlVisual studioWindowsXml

Using Fonts and Color in Applets


+ Font mai mare | - Font mai mic


Trimite pe Messenger
Introduction to objects
Comments and embedded documentation
Raw Native Interface (RNI)
Calling constructors from constructors
Performing cleanup with finally: Whatís finally for?
The new AWT: The new event model
Arrays are first-class objects
Seam Contexts
The comma operator

Using Fonts and Color in Applets

A famous catchphrase from the television show Saturday Night Live during the 1980s was, 'It's not how you feel, but how you lookand darling, you look MAH-ve-lous.' The quote epitomized the philosophy of Fernando, comedian Billy Crystal's eternally tan and impeccably groomed celebrity. Regardless of what was going on in his life, as long as his hair was styled properly and he was dressed for the occasion, everything was copacetic. After all, though Fernando hadn't been in a hit movie since Won Ton Ton, the Dog Who Saved Hollywood, he still looked good. Correction: He looked MAH-ve-lous.

If you're interested in making your Java applets look MAH-ve-lous, you should know about the Font and Color classes. No self-respecting applet would be seen in public without them. With these classes, you can present text in several different fonts and sizes and change the colors of text, graphics, and other elements.

One of the principles of object-oriented programming is to make an object work for itself, and the Font and Color objects follow this rule. They store all the information that's needed to display a font or change a color, and they can handle other related tasks that are required. The following topics will be covered during this hour:

Using fonts in your applets

Setting a font's style and size

Choosing a font

Displaying colors in applets

Using the color constants

Setting up the background color

Using RGB values to choose colors

Using HSB values to choose colors

Creating special text effects using colors

Using the Font Class

There are three things you need to know about a font in order to display it:

The typeface of the font: Helvetica, Courier, Dialog, Times Roman, or others

The style of the font: bold, italic, or plain

The size of the font, in points

Before you can display text in a certain typeface, style, and point size, you need to create a Font object that holds this information. The following statement creates a 12-point Times Roman italic Font object:

Font currentFont = new Font('TimesRoman', Font.ITALIC, 12);

The typeface that you can select may vary depending on the system you're using. The current release of the Java Developer's Kit for Windows 95 includes Helvetica, Courier, Dialog, Dialog Input, and Times Roman.

You choose the style of the font by using one or more constant variables. Specifying the style as Font.PLAIN makes it nonbold and nonitalic, Font.BOLD makes it bold, and Font.ITALIC makes it italic. To combine bold and italic, use Font.BOLD+Font.ITALIC, as in the following code:

Font headlineFont = new Font('Courier', Font.BOLD+Font.ITALIC, 72);

The last argument specifies the point size of the font. To see a simple example of using fonts in an applet, open your word processor and create a new file called Enter the text of Listing 16.1 and save the file.

Listing 16.1. The full text of

1: import java.awt.*;


3: public class Fonts extends java.applet.Applet

After you compile the file with the javac compiler tool, you need to create a Web page that contains the applet. Create a new file in your word processor called Fonts.html and enter the text of Listing 16.2.

Listing 16.2. The full text of Fonts.html.

1: <applet code='Fonts.class' height=125 width=450>

2: </applet>

Save this file and then load this page into the appletviewer tool by using the following command:

appletviewer Fonts.html

The output should resemble Figure 16.1.

Figure 16.1. <../art/16/16tja01.jpg> The output of the Fonts applet.

Using the Color Class

The simplest way to use a color in a Java program is to use one of the constant variables from the Color class. You can use the following constants: black, blue, cyan, darkGray, gray, green, lightGray, magenta, orange, pink, red, white, and yellow.

In an applet, you can set the background color of the applet window using these constants. The following is an example:


When you want to display text of a certain color or draw other graphics in different colors, you have to use a method that sets up the current color. You can do this from within the paint() method of an applet by using a setColor() method, as in the following:

public void paint(Graphics screen)

Unlike the setBackground() method, which is inherited directly from the Applet class, the setColor() method must be used on an object that can handle a color change. The preceding example shows the setColor() method of the screen object being used to change the current color of the applet window.

Other Ways to Choose Colors

To use a color not included in the 13 constant variables, you must specify the color's RGB or HSB values. RGB, which stands for Red Green Blue, defines a color by the amount of red, green, and blue that is present in the color. Each value ranges from 0, which means there is none of that color, to 255, which means the maximum amount of that color is present. Most graphics editing and drawing programs will identify a color's RGB values.

If you know a color's RGB values, you can use it to create a Color object. For example, an RGB value for dark red is 235 red, 50 green, and 50 blue, and an RGB value for light orange is 230 red, 220 green, and 0 blue. The following is an example of an applet that displays dark red text on a light orange background:

import java.awt.*;

public class GoBucs extends java.applet.Applet

public void paint(Graphics screen)

Dark red on a light orange background isn't much more attractive on a Java applet than it is on the National Football League's Tampa Bay Buccaneers. Using RGB values enables you to select from more than 16.5 million possible combinations, although most computer monitors can only offer a close approximation for most of them. For guidance on whether light-light-light-semidark-midnight-blue goes well with medium-light-semidark-baby-green, purchase a copy of the upcoming Teach Yourself Color Sense While Waiting in Line at This Bookstore from Publishing.

Another way to select a color in a Java program is the HSB system, which stands for Hue Saturation Brightness. Each of these is a floating-point number that ranges from 0.0 to 1.0. The HSB system isn't as commonly supported in graphics software, so you won't be using it as often in your programs as you use RGB values. However, one thing HSB values are convenient for is changing a color's brightness without changing anything else about the color. You'll see an example of this use and an example of using HSB values to choose a color in this hour's workshop.

Workshop: Displaying a Danger Message

You can use Java applets to present news headlines and other information in different ways. One special effect you might see on a Web page is text that fades to black. You also might see the reverse--text that brightens from black to white. This hour's workshop uses the Font and Color classes to create text that cycles in brightness from dark to bright. The text looks like an alert about impending danger, so the applet will be called Danger.

To make the applet more useful, the text of the warning will be set from a parameter on a Web page. The text that will be used in this example warns of a 'Core breach in Sector 12,' but you can substitute other threatening text of similar length.

If you're at a secure place in your life right now and can't think of anything suitably menacing, feel free to choose one of the following:

'Mother-in-law wants to visit'

'Boss approaching'

'Dallas Cowboys scheduled to play here'

'We have no bananas today'

'No hamburger--cheeseburger'

Create a new file in your word processor called Each section of the applet will be described as you enter it. Begin with the following statements:

import java.awt.*;

public class Danger extends java.applet.Applet

The init() method is handled once when the applet is first run, and then it is never handled again. It's a good place to set up some things that weren't set up when variables and objects were created. The first thing that happens in this method is the background of the applet is set to black by using the setBackground() method inherited by Danger from the Applet class.

Next, the parameter called TEXT is retrieved from the Web page that contains this applet. If no parameter is found, the default text stored in text will be displayed. Otherwise, the text specified by the parameter will be stored in text.

The FontMetrics class measures how wide a line of text will appear when it is displayed. Using the stringWidth() method of FontMetrics and the applet's size() method, you can center text on-screen. The textX variable stores the horizontal position where the text should be displayed.

Now continue by entering the paint() method of your class, which is called whenever the display on-screen needs to be updated. Leave a blank line after the init() method and enter the following:

public void paint(Graphics screen)


The paint() method takes a Graphics object called screen as an argument. This object holds all the information needed to display something on-screen, and it has several methods you'll use.

The Color object called textColor is created using the HSB variables to select the color. The textColor object then becomes the current display color using the setColor() method of screen.

Using the drawString() method of screen, the variable text is displayed at the (x,y) position of textX and 30. The color of the text is the current display color. After the text has been displayed, a pause() method is called with an argument of 250,000. You'll see what this method does when you add it to your program.

In order for the text to change in brightness, you have to change the value of the brightness variable. The program increases the variable .05 (a 5 percent change), and if the variable has reached the maximum brightness of 1.0, it is reset to 0.0. Whenever brightness must be reset to 0.0, the program calls the pause() method.

The last thing that takes place in the paint() method is the repaint(); statement. You use this statement any time you need to redraw the screen because something has changed. Because the brightness variable has changed, you know there's a need to redisplay the text at the new brightness. The repaint() statement causes the paint() method to begin again.

The paint() method handles most of the work that takes place during the Danger applet. All you have left to add are two short methods called update() and pause(). Enter a blank line at the end of your program, and then continue with the following statements:

public void update(Graphics screen)

void pause(int duration)

The update()method is one of the methods that normally works behind the scenes as an applet runs. It is handled any time the screen needs to be repainted or the repaint() statement is used. The update() method clears the screen and calls on paint() to do its work. However, clearing the screen when you're changing graphics or text often causes things to flicker badly in a Java program. In this code, you're overriding the update() method so it does not clear the screen at all, which will improve the quality of your applet's display. You'll learn more about this procedure during Hour 18, 'Creating Animation.'

The last thing in your applet is the pause() method, which takes an argument called duration. The method runs an empty for loop ranging from 0 to the value of duration. This loop causes the program to pause. The higher the value of duration, the longer the pause. When you are displaying changing graphics or text, you might need pauses of some kind to prevent things from changing too quickly. This pause() method is one way to create these pauses.

Save the file, which should resemble Listing 16.3. The only difference might be in the way you have indented methods and other statements. That does not have to be changed in order for the program to run, but indentation and other spacing can make a program easier to understand.

Listing 16.3. The full text of

1: import java.awt.*;


3: public class Danger extends java.applet.Applet

public void paint(Graphics screen)



public void update(Graphics screen)

void pause(int duration)

After compiling the file with the javac compiler tool, you need to create a Web page that contains the Danger applet. Create a new file with your word processor called Danger.html, and enter the text of Listing 16.4 into the file.

Listing 16.4. The full text of Danger.html.

1: <applet code='Danger.class' height=60 width=400>

2: <param name='TEXT' value='Core breach in Sector 12'>

3: </applet>

You can change the value in Line 2 to any other menacing sounding text, as long as it is similar in size to Core breach in Sector 12. Use the appletviewer tool to view the Web page with the following command:

appletviewer Danger.html

Figure 16.2 shows the output of the Danger applet.

Figure 16.2. <../art/16/16tja02.jpg> A screen capture of the Danger applet as it runs with the appletviewer tool.


Now that you can use Font and Color objects in your programs to change the color scheme, you can no longer feign ignorance when it comes to designing an attractive applet. By using fonts and color instead of sticking to the familiar black text on a light gray background, you can draw more attention to elements of your programs and make them more compelling for users. You also, of course, can write programs that look MAH-ve-lous. It's what Fernando would want you to do.


Q Is there a limit to the point size that can be used for text?

The limiting factor is the height and width of your applet window or the part of an applet the text is supposed to be displayed in. Point sizes typically range from 9-point text for small lines that are readable to 48-point text for large headlines. Choosing the right size depends on the font typeface as well as the size, so it's largely a matter of trial and error.

Q What happens if a color defined in a Java program can't be displayed on the monitor of someone displaying the program? For example, if my monitor is set to display only 256 colors, what will occur if I choose one of the 16.5 million colors that isn't in those 256?

When a monitor can't display a color selected with a
setColor() or setBackground() method, it shows the closest existing color as a substitute. An example of this kind of substitution is the Danger applet, which runs differently depending on the number of colors that can be shown as the text cycles from black to light blue to white.


Test whether your font and color skills are MAH-ve-lous by answering the following questions.


Which one of the following is not a constant used to select a color?


When you change the color of something and redraw it on an applet window, what must you do to make it visible?

(a) Use the
drawColor() method.
(b) Use the
repaint() statement.
(c) Do nothing.

What do the initials HSB stand for?

(a) Hue Saturation Brightness
(b) Hue Shadows Balance
(c) Lucy in the Sky with Diamonds



b. The call to
repaint() causes the paint() method to be manually called.

a. If c were the right answer, you could use colors that would only be visible years later during flashbacks.


To further explore the spectrum of possibilities when using fonts and color in your programs, do the following activities:

Remove the update() method from the Danger applet to see what effect it has on the quality of the display.

Add a way to specify the background of the Danger applet by sending parameters for the RGB values of the desired background color.

Politica de confidentialitate



Vizualizari: 389
Importanta: rank

Comenteaza documentul:

Te rugam sa te autentifici sau sa iti faci cont pentru a putea comenta

Creaza cont nou

Termeni si conditii de utilizare | Contact
© SCRIGROUP 2021 . All rights reserved

Distribuie URL

Adauga cod HTML in site