Приглашаем посетить
Гумилев (gumilev.lit-info.ru)

3.2 Controlling fonts and colors with Java applets

Table of Contents

Previous Next

3.2 Controlling fonts and colors with Java applets

Undoubtedly, one of the most popular applications of using Java is through embedding applets in HTML/XHTML pages. An applet, in general, is a small program which will run automatically when downloaded into the browser. Java applets are applet programs written in Java. Throughout this chapter, the word applet refers to a Java applet.

3.2.1 A simple Java applet

Let's convert the first Java program HelloWorld.java into an applet. Generally you need to perform the following tasks when creating any applet applications:

  • Create a Java program to generate the applet application.

  • Compile the source code files into bytecode or class.

  • Create an HTML/XHTML page and use the applet element <applet> to call the class.

Consider the following Java code HelloWorldApplet.java:



Example: HelloWorldApplet.java - Hello World Applet

 1: import java.awt.*;
 2: import java.applet.*;
 3:
 4: public class HelloWorldApplet extends Applet
 5: {
 6:   public void paint (Graphics g)
 7:   {
 8:     g.drawString("Hello World! - My First Applet",10,10);
 9:   }
10: }

This Java applet is slightly longer than the HelloWorld.java program. First, in order to generate applet code and use it in a browser, two Java packages (or class libraries) are included as illustrated in lines 1 and 2. Line 1 includes the package called java.awt (Java Abstract Windowing Toolkit). This package provides a number of interface features such as controlling windows, creating controls, fonts, images, and drawings which, in many cases, are necessary for the integration of Java code and the associated Web page. The java.applet package provides the capability of generating code to be used inside a Web page. The asterisk "*" at the end means that all public classes from the named package are imported. The Java statement in line 4 will generate a class called HelloWorldApplet and will be executed by a Web page. Inside this class, we have a public method (see lines 69):



public void paint (Graphics g)
{
  g.drawString("Hello World! - My First Applet",10,10);
}

This method is supplied with a graphics object graphics by the local system and transfers it to the variable g. The function g.drawString() is to output the text 'Hello World! - My First Applet" to the applet window at the pixel position (10, 10) from the top left corner of the window. To call this Java applet, the following XHTML element is used:



<applet code="name_of_applet_class" width=m height=n> </applet>

where name_of_applet_class is the name of the applet class, and the parameters m and n define the size of the applet window. After you have compiled the Java program HelloWorldApplet.java successfully, you can use the applet element above to execute the associated bytecode (or class). Consider our first Web page ex03-01.htm to call the Java applet:



Example: ex03-01.htm - Hello World Applet

 1: <?xml version="1.0" encoding="UTF-8"?>
 2: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN"
 3: "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
 4: <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 5: <head>
 6: <title>Hello World Applet  ex03-01.htm</title>
 7: </head>
 8: <body style="font-size:28pt; text-align:center;font-weight:bold">
 9:   Embedding Java Applet Using XHTML<br />
10: <applet code="HelloWorldApplet.class" width=200 height=50>
11: </applet>
12: </body>
13: </html>

This page will call the Java applet HelloWorldApplet.class and run the program inside the applet window. A screen shot of this example is shown in Fig. 3.3.

Figure 3.3. ex03-01.htm

graphics/03fig03.gif


You now know how to include a Java applet in a Web page and display a message. The next step is to control the font and color. More importantly, we will show you how to incorporate graphics into XHTML documents.

3.2.2 A Java applet to set font and color

Unlike many other Web technologies, Java applets are not just programs that you can embed into your Web pages and run. Strictly speaking, applets are not run by the calling browsers. A Java-enabled browser passes any Java applications to the JVM or JRE and therefore Java programs will run unchanged whatever the host platform, achieving the so-called what-you-see-is-what-you-get (WYSIWYG) feature. For example, different systems such as Windows and LINUX may handle fonts and their associated font properties in a different way. If you want your Web page to have the same font, font metric, or displaying effect across different operating systems and browsers, Java may be a solution for you.

Consider the following Java program:



Example: Font01.java - Using Font And Color

 1: import java.awt.*;
 2: import java.applet.*;
 3:
 4: public class Font01 extends Applet
 5: {
 6:  public void paint(Graphics gg)
 7:  {
 8:    Graphics2D g = (Graphics2D) gg;
 9:
10:    g.setFont( new Font("Arial",Font.BOLD,26) );
11:    g.setColor(Color.blue);
12:
13:    g.drawString("This is Java Applet",20,60);
14:    g.drawString("Arial Font, Bold, Size:26",20,90);
15:    g.drawString("Text Color:blue",20,120);
16:  }
17: }

This program is similar to the HelloWorldApplet mentioned in section 3.2.1. The only main difference is that we have added lines 811 to set the displaying font and color. The statement in line 8



Graphics2D g = (Graphics2D) gg;

sets up an instance of class Graphics2D from the package java.awt so that the object variable g will have the capability to handle more advanced graphics. The class Graphics2D is, in fact, a subclass of "Graphics" containing some more advanced 2D graphics capabilities. Although it is not very important for this example, it is essential for our examples later in this chapter.

Once you have the graphics g, to set up the displaying font is just a simple process. For example, you can call the function setFont() to define a font style as demonstrated in line 10, i.e.,



g.setFont( new Font("Arial", Font.BOLD, 26) );

In this case, the default drawing font is Arial, bold, and a size of 26 points (1 point = 1/72 inch). In addition to the Font.BOLD style some other options for the font style are Font.PLAIN and Font.ITALIC. If you want to set bold and italic combinations, you can use the following:



Font.BOLD + Font.Italic

The function (or method) g.setColor() in line 11 is used to set the drawing color as blue. Some other color options are listed in Table 3.1.

Table 3.1. Java color constants

Color.darkGray

Color.yellow

Color.red

Color.black

Color.orange

Color.green

Color.lightGray

Color.magenta

Color.blue

Color.gray

Color.cyan

 

Color.white

Color.pink

 


To call this Java applet, all you need is to replace the body part (lines 812) of ex03-01.htm by the XHTML code fragment in ex03-01.txt and call it ex03-02.htm.



Listing: ex03-01.txt - XHTML Code Fragment For Example ex03-02.htm

1: <body style="font-size:18pt; text-align:center;font-weight:bold">
2:   Java Applet: Font And Color<br />
3:   <applet code="Font01.class" width=450 height=400>
4:   </applet>
5: </body>

A screen shot of this example in action is shown in Fig. 3.4.

Figure 3.4. ex03-02.htm

graphics/03fig04.gif


3.2.3 Font rotation and translation

With Java, graphical objects can be manipulated easily. For example, rotation and translation can be performed on a Web page without any complications. This feature greatly enhances the functionality of XHTML documents. To translate a graphical object, you can use the function



translate(xpos,ypos)

This command will translate the origin to the coordinate position (xpos,ypos). To rotate a graphical object, the following function can be used:



rotate(angle_in_radian)

This function will rotate the coordinate system to an angle measured in radians. A positive angle value rotates the object in a anti-clockwise direction. The combination of rotation and translation, in many cases, can be used to create special effects. Consider the XHTML page ex03-03.htm:



Example: ex03-03.htm - Font Rotation And Translation

 1: <?xml version="1.0" encoding="UTF-8"?>
 2: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN"
 3:   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
 4: <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 5: <head>
 6:    <title>Font Rotation and Translation  ex03-03.htm</title>
 7: </head>
 8: <body style="font-size:18pt; text-align:center;font-weight:bold">
 9:   Font Rotation And Translation<br /><br />
10:   <applet code="Font02.class" width=450 height=400>
11:     <param name="text" value="....Web Technology">
12:     <param name="size" value="18">
13:   </applet>
14: </body>
15: </html>

This is a simple page with one applet element (lines 1013) to call the Java program: Font02.class. The applet element also contains two parameter elements (i.e., <param>) which can be used to pass values to the Java class. For example, the first parameter element (see line 11)



<param name="text" value="....Web Technology">

specifies a parameter called text. The value of this text is "....Web Technology." The Java function



textV = getParameter("text");

can be used to identify the parameter text, get the string value, and assign the string to variable textV. The parameter in line 12 is to pass the font size 18 to the Font02.class program. The parameter element <param> provides a useful way to pass values to Java programs.

As a simple example, the program Font02.class will only translate and rotate the string to form a circle. A screen shot is shown in Fig. 3.5.

Figure 3.5. ex03-03.htm

graphics/03fig05.gif


As you can see from Fig. 3.5, the string is first translated to near the center of the page and then rotates the text to give a circle. The actual Java code to do the rotation and translation is provided in the following example.



Example: Font02.java - Rotation And Translation

 1: import java.awt.*;
 2: import java.applet.*;
 3:
 4: public class Font02 extends Applet
 5: {
 6:  String tmpSt, textV;
 7:  int sizeV;
 8:
 9:  public void init()
10:  {
11:    textV = getParameter("text");
12:
13:    tmpSt= getParameter("size");
14:    sizeV = Integer.parseInt(tmpSt);
15:  }
16:
17:  public void paint(Graphics gg)
18:  {
19:    int ii;
20:
21:    Graphics2D g = (Graphics2D) gg;
22:    g.setFont( new Font("Arial",Font.BOLD,sizeV) );
23:    g.setColor(Color.blue);
24:
25:    g.translate(200,200);
26:    for (ii=1;ii<=16;ii++)
27:    {
28:      g.rotate(Math.PI/8.0);
29:      g.drawString(textV,20,0);
30:    }
31:  }
32: }

This Java applet code contains two functions. The first function init() (i.e., initialization) will be executed after the program is loaded. The getParameter() functions in line 1112 are used to get the text and font size from the XHTML page. Since values from the Web page are considered as strings, the Integer.parseInt() function in line 14 is employed to convert the text string into an integer.

The font size variable sizeV is used in line 22 to define the font. After setting the drawing color to blue in line 23, the function



g.translate(200,200)

is called to translate the origin to new position (200, 200). The for-loop in lines 2630 is to rotate the text 16 times. Each rotation will be done with an angle equal to PI/8.0 radians. For each rotation, the text from the Web page is displayed. After 16 rotations, the text string is rotated 2*PI radians (i.e., 360 degrees) which is a complete circle. Now, let's see how to add colors to the circular text string.

3.2.4 A page with random colors

The color constants listed in Table 3.1 are a convenient way to specify standard colors for a drawing process. If you want to use more colors, the Color() function (or object) may be more suitable. For example, the following command will use the Color() function to set the current color as blue, which will have the same effect as the color constant Color.blue:



setColor( new Color(0,0,255) )

The Color() function takes three integers from 0 to 255, each representing the red (R), green (G), and blue (B) components. For example, Color(255,0,0) represents the red color, the same as the color constant Color.red. The combinations of all (R, G, B) components yield a total of more than 16 millions colors.

If you replace the paint() function in the Java program Font02.java by the Java code below, you will have a new Java program called Font03.java (Don't forget to change the applet name in line 4 to Font03).



Listing: ex03-02.txt - Java Code Fragment For Font03.java

 1:  public void paint(Graphics gg)
 2:  {
 3:    int ii;
 4:
 5:    Graphics2D g = (Graphics2D) gg;
 6:    g.setFont( new Font("Arial",Font.BOLD,sizeV) );
 7:
 8:
 9:    g.translate(200,200);
10:    for (ii=1;ii<=16;ii++)
11:    {
12:      g.rotate(Math.PI/8.0);
13:      g.setColor( new Color((int) (Math.random()*256),
14:                            (int) (Math.random()*256),
15:                            (int) (Math.random()*256)) );
16:      g.drawString(textV,20,0);
17:   }
18: }

If you compare this paint() function with the one in Font02.java, you will find that a setColor() statement is added in lines 1315. The function



Color( (int) (Math.random()*256),
       (int) (Math.random()*256),
       (int) (Math.random()*256))

returns a color in terms of random red, green, and blue (i.e., RGB) mode. The mathematical function Math.random returns a random value between 0 and 1. The expression (int) (Math.random()*256) provides a random value between 0 and 255 for each RGB component. The setColor() function in line 13 sets the random color as the drawing color and therefore you have a random color effect.

Now, replace line 10 of ex03-03.htm by the following line and call it example ex03-04.htm:



10: <applet code="Font03.class" width=450 height=400>

This new example executes the Java program Font03.class to generate random colors on the text circle. Whenever the page is called, a new set of colors will be displayed. A screen shot of this example is shown in Fig. 3.6.

Figure 3.6. ex03-04.htm

graphics/03fig06.gif


3.2.5 Selecting color with JColorChooser()

When it comes to practical use, a color-choosing dialog window may be more convenient for your clients or users. Java provides a standard color chooser called JColorChooser() so that users from different computing platforms can have the same color controlling mechanism. This JColorChooser() function (or method) will open a dialog window and allow you to pick a color dynamically. By following the next example, you can develop a page to activate the JColorChooser() so that the text color can be changed dynamically.

First, we want to set up a color button called ColorButton so that the color-picking box ColorChooser() can be activated by a simple mouse click. To build a button in Java, you can use the code



public void init()
{
  ColorButton = new Button("Activate JColorChooser");
  add(ColorButton);
  ColorButton.addActionListener(this);
}

The new Button() statement creates a button called ColorButton with label "Activate JColorChooser." The add() function is used to display the created button on the Java page. In order to listen to any mouse click on this button, you need to set up the so-called action listener or the addActionListener() function associated with the button ColorButton. In general, we would like the button to be created at the beginning of our Java program and therefore all statements are put inside a function called init() (i.e., initialization).

When you set up an action listener function, you need to develop a function called actionPerformed() to handle an event such as the button click. The actionPerformed() function in this case is defined as



public void actionPerformed ( ActionEvent event)
{
 color = JColorChooser.showDialog(
           ColorChooser.this,
           "Select Your Color", color );
 if ( color == null )
    color = Color.blue;
 repaint();
}

When there is a click on the button ColorButton, this function will be activated. The JColorChooser.showDialog() function opens a dialog window with the title "Select Your Color." This dialog window will attach to the Java program as specified by the first argument ColorChooser.this. You can pick a color dynamically inside the window and the selected color will be returned to the variable color. If there is no color selected, the default color is set to be blue (i.e., Color.blue). The repaint() function causes the page to redraw so that the newly selected color will take effect immediately.

To put the discussion above into action, consider the first part of the Java program ColorChooser.java.



Example: ColorChooser.java - To Pick A Color (Part One)

 1: import java.awt.*;
 2: import javax.swing.*;
 3: import java.awt.event.*;
 4: import java.applet.*;
 5:
 6: public class ColorChooser extends Applet implements ActionListener
 7: {
 8:   private Button ColorButton;
 9:   private Color color = Color.blue;
10:
11:   public void init()
12:   {
13:     ColorButton = new Button("Activate JColorChooser");
14:     add(ColorButton);
15:     ColorButton.addActionListener(this);
16:   }
17:
18:   public void actionPerformed( ActionEvent event)
19:   {
20:    color = JColorChooser.showDialog(
21:              ColorChooser.this,
22:              "Select Your Color", color );
23:
24:    if ( color == null )
25:       color = Color.blue;
26:    repaint();
27:   }
28:

In order to handle mouse clicks and events, the packages javax.swing and java.awt.event are imported as illustrated in lines 2 and 3. The statement in line 6 specifies that the Java applet that we are going to generate is called ColorChooser, which includes an ActionListener. Inside this ColorChooser class, two private variables are used so that the variables cannot be easily changed by other classes or functions. The first variable defines a button called ColorButton and the second variable specifies a color with initial value Color.blue (i.e., blue color).

The init() function is to generate the button and set up the action listener. The details of the action response function actionPerformed() are defined in lines 1827.

Now, you need to construct the paint() function so that it will respond to the repaint() function call as in line 26. The paint() function is a simple one and is listed in the second part of this Java code:



Listing: Continuation Of The Java Program ColorChooser.java

29:   public void paint(Graphics gg)
30:   {
31:    Graphics2D g = (Graphics2D) gg;
32:
33:    g.setFont( new Font("Arial",Font.BOLD,26) );
34:    g.setColor(color);
35:
36:    g.drawString("This is a text message",20,80);
37:    g.drawString("You can select and change the color",20,110);
38:    g.drawString("using the Java JColorChooser",20,140);
39:   }
40: }
41:

This Java code contains only one function, paint(). This function is very similar to the function mentioned in previous examples. The main feature of this function is line 34 which is used to set the current color as the newly selected color from the JColorChooser() dialog window. The color of the text will be changed immediately. If you replace the body part of ex03-02.htm by the XHTML code in ex03-03.txt and call it example ex03-05.htm, you will have a Web page to call the applet and make color selections. Some screen shots are shown in Figs. 3.73.10.



Listing: ex03-03.txt - Code Fragment For Example ex03-05.htm

 1: <body style="font-size:22pt; text-align:center;font-weight:bold">
 2:   Select and Change Color With <br />The JColorChooser<br /><br />
 3:
 4:   <applet code="ColorChooser.class" width=500 height=200>
 5:   </applet>
 6: </body>

Figure 3.7. ex03-05.htm

graphics/03fig07.jpg


Figure 3.10. Change text color dynamically

graphics/03fig10.jpg


There are three coloring methods to define a color in JColorChooser(). Fig. 3.8 demonstrates the so-called "Switch" method. Your mouse can pick any color inside the window and switch the color in your application. Figure 3.9 illustrates the RGB coloring method. You can use your mouse to select the color by changing the RGB value on the slide bar. After the OK button is pressed, the color of the text will be changed immediately as in Fig. 3.10.

Figure 3.8. The JColorChooser() dialog window I (switch)

graphics/03fig08.jpg


Figure 3.9. The JColorChooser() dialog window II (RGB)

graphics/03fig09.jpg


It's now time to consider how to use graphics on Web pages.

    Table of Contents

    Previous Next