Assignment 6 - Using Iteration
In this homework, you'll build an applet that uses looping, String methods, and the applet getParameter() method to build the "ColorTicker" applet which you can see running at the top of your screen. Before you start this you should know how to simple selection and iteration statements.
This includes:
- Knowing how to use relational operators to form boolean expressions
- Knowing how to combine boolean expressions with the logical operators to produce compound boolean expressions
- How to write the init() and paint() methods
- How to create a FontMetrics object and retrieve Font information from it.
- How to convert String values to int values
This homework covers the material from Lesson 6, and a little from Lesson 8 [the String methods charAt() and substring()]. You should have at least read through the material once before getting started, otherwise, you'll find yourself wasting a lot of effort.
To complete the homework you'll have to understand:
- How to use the getParameter() method to retrieve values from an HTML page. This is not explained in your text, but was discussed in Lesson 6.6.
- How to check if a value was received from getParameter(), and how to anticipate different problems.
- How to use a loop to compute a series of color values.
- How to use the String methods charAt() and substring() to repeatedly process a String object.
Step-By-Step Instructions
Step 1
Write the applet skeleton. Call your applet ColorTicker. Your applet will use classes from the following packages:
Make sure you enter your personal information to the top of your source code. Add your name, your class, your Java ID number [s2188100XXX], and a brief description of the program. Every program you write should include this information.
Next, add the following attributes [fields] to your class:
1. A String field called motd
- This will hold, appropriately, the message-of-the-day
- Initialize motd to any catchy phrase you like. (Remember, though, that this is a Community college.)
2. An int field called waitTime
- This will hold the number of milliseconds to wait before repainting, so the ticker doesn't go by too fast.
- Begin by initializing waitTime to hold 100
3. Three int fields called stepRed, stepBlue, and stepGreen
- These will control the color effects as your slogan is painted.
- Begin by initializing the three fields to 2, 3, and 7 respectively
4. A Color field called msgColor
- This will be used, along with the step values you just created, to cycle through a range of colors.
- Initialize msgColor to any color you like.
Step 2
Write the init() method. Here are the tasks you'll need to accomplish. You might want to recompile after completing each task, just to make sure you get it right.
- Create a local String object named fontName, and initialize it to the name of a Java font, such as "Helvetica", "TimesRoman", or "Courier." Create a local int variable named fontSize and initialize it to the size you want to use for your font, in points. (72 points is an inch). Create a local Font object that will be used to display your slogan. Use the variables fontName and fontSize as the first and third arguments to the Font constructor. Use Font.BOLD for the second.
- Send the setFont() message to your applet, to make sure your new Font is used throughout your applet.
Step 3
Add the paint() method. You'll use the paint() method to display your slogan. Instead of just using a single drawString(), however, as you did with DateDisplay, you'll use iteration to paint each character in a different color. Here are the steps to follow:
1. Create a method skeleton
The paint() method must be public and it returns void. The single argument to the paint() method is a Graphics object (call it g). You must write this correctly for your applet to work. Once you've written the method header, add the braces for the body
2. Calculate the position to display your slogan
This requires several pieces of information, such as how high and wide your applet is, and how many pixels are required to render your message, given the current font. We'll center the message horizontally inside the applet and leave a 25-pixel border along the bottom border.
Here's what you need to do:
- Send the Graphics object named g a getFontMetrics() message. It will reply by creating a FontMetrics object and returning it to you. Store the result in a local FontMetrics variable named fm. Send the FontMetrics object, fm, the stringWidth() message, passing your String field named motd as the argument. It will reply by telling you how many pixels are required to paint your message of the day. Store the result in a local int variable named pixWidth. Calculate the width of your applet by sending it the size().width message. Store the result in a local int variable called appWidth. [Note that there are parentheses after size but not after width. These are separated by a dot.] Subtract pixWidth from appWidth, and divide the result by two. Store the result of the division in a local int variable named xPos. (Note, xPos will normally be negative, because pixWidth will normally be larger than appWidth. This is fine.)
- Calculate the height of your applet by sending it the size().height message. Subtract 25 from the answer you receive back, and store the result in a local int variable called yPos.
3. Display the slogan contained in the String motd
Rather than drawing the entire message with one call to drawString(), you're going to draw each character individually. To do that, you need to find out how many characters are in your String and then use a loop to draw a single character. In your loop you'll advance the value of xPos by the width of that single character, and then draw the next character, until the entire String is displayed.
Here are the steps to accomplish that:
- Create a local int variable named len, to hold the number of characters in your message. Initialize len, by sending your String--motd--the length() message. Your String will reply by telling you how many characters it contains. Store the answer in len. Write a for loop that starts at zero and goes to len - 1. (Use i < len to make sure the counter stops at len-1, not i < len - 1.)
- Inside the body of the for loop use the loop counter to carry out the following tasks:
- Create a local char variable named ch. Send the charAt() message to the String motd, passing your loop counter as the argument. Store the result in the variable ch. (On the first revolution of your loop, you'll call motd.charAt(0), on the second, motd.charAt(1), and so on.) Use the Graphics drawString() method to paint the character ch at xPos, yPos. Because drawString() expects a String as its first argument, instead of a char, you'll have to create a temporary String by passing the expression "" + ch as the first argument to drawString().
- Use the FontMetrics method, charWidth(), to find out how wide the character ch is, in pixels. Add the value returned from calling charWidth() to the variable xPos.
4. "Rotate" the characters inside the motd field
This gives the illusion that the characters are moving. These steps should be placed after the body of the loop used in the previous section.
Here are the steps to follow:
- You've seen that the String method charAt() returns the individual characters contained in a String. The first character is charAt(0), the second charAt(1), and so forth. The last character is charAt(len-1). Use charAt() to get the first character in motd and save it in a local char variable. The String method substring() works a little like charAt() but instead of returning a single character located at a particular offset, it returns the entire substring that begins at that offset. If the String varaible named s contains "Hello", for instance, then the expression s.substring(1) returns the String "ello", while s.substring(3) returns "lo". Use the substring() method to create a String that contains all of the characters in motd, except the first character.
- To finish rotating the String motd, simply "paste" the old first character of motd (which you extracted by using the charAt() method) on to the end of the portion of motd which you retrieved by using the substring() method. Use the String concatenation operator (+) to paste the two pieces together, and assign the result back to motd.
5. Repaint the Message of the Day
The final step in the paint() method is to call the repaint() method. Right before calling repaint(), however, add the following lines of code, which will ensure that your phrase scrolls smoothly:
try
{
Thread.sleep(waitTime);
}
catch(InterruptedException e) { }
At this point, your applet is ready to run. Create an HTML file, and try it out. Your program should look like this:
Step 4
Add some color to your message. For this, you'll use the Color field, msgColor, that you created in Step 1. Here are the steps to follow:
1. Create some color variables
This code must go inside the paint() method, but before the loop that contains the drawString().
- Create three local int variables named red, blu, and grn. Send the getRed() message to the msgColor field, and store the result in the variable red.
- Do the same thing with the other two variables, using the getBlue() and getGreen() messages.
2. Update the color variables
This code must go inside the drawing loop, before the characters are actually displayed:
- Add the appropriate step value to each of the color variables. Add stepRed to red, stepBlue to blu, and stepGreen to grn. Use the modulus operator to restrict red, blu, and grn to a value between 0 and 255. If you have any large positive integer n, you can reduce it to a number between 0 and x-1 with the expression n = n % x; or, using the shorthand assignment operators, n %= x; After updating red, grn, and blu, use the Color(int, int, int) constructor to create a new Color object, and assign it to msgColor. Pass the arguments to the constructor in the order: red, grn, blu.
- Send the setColor() message to your Graphics object named g, passing msgColor as the argument.
At this point, you should be able to recompile, and your applet should look like this:
Step 5
Allow the user to change the text that's displayed. This part is pretty easy. Just make use of the getParameter() method. The getParameter(name) method is part of the applet class. It allows you to pass arguments from HTML to your Java applet. Thus, you can use the same applet and have it display different text or use different colors. Let's use getParameter() to retrieve a custom message. Here's how:
After you've written the if statement, compile and run the program, to make sure it still works. Since you haven't supplied an HTML PARAM tag, it should work just like it did before. If it doesn't, you've made a logic or syntax error.
- Once the program compiles and runs satisfactorily, modify your HTML file to add this tag in between the <applet> and </applet> tags:
<param name="message"
value="Your Message Here">
Compile and run, and make sure that your applet shows the new message.
Step 6
Allow the user to change Fonts and Colors. The general process is pretty similar to what you did for the message tag. Here are the four steps you'll follow for each parameter you want to pass from your HTML page into your Java applet.
- Create a String variable to hold the value from the HTML file.
- Call getParameter() with the name of the particular parameter you wish
to retrieve. The name will be the same as the name attribute used in the PARAM tag.
- Check the returned value against null. If it is null, then assign some default value to the receiving String.
- If the actual value you need is an integer, like the stepRed, stepGreen, and stepBlue variables, you'll need to call Integer.parseInt() on the String returned by getParameter() to do the conversion.
Use these steps to add the following tags to your HTML file. In addition, you'll need to check for each tag, using the getParameter() method, inside your applet's init() method
- stepRed, stepGreen, stepBlue. These are int parameters that determine how much each color will be advanced when the next character is printed. The default values are 2, 3 and 7.
- fontSize. This is an int parameter that will be used at the bottom of the init() method to create the applet's default Font.
- fontName. This is a String parameter used, along with fontSize, to create the applet's default Font.
- waitTime. This is an int parameter that is used to tell the browser how long to wait (in milliseconds) before repainting. The smaller the value, the faster the animation will run, the larger the value, the slower it will run. The default value is 100 ms.
Finishing Up
Post your applet. Once you've tested your applet locally, add it to the Assignment 6 HTML file on your Web site.
Do not send your source code to your Web site. Also, make sure you have added the necessary PARAM tags to your HTML file.
|