TweetFollow Us on Twitter

Blinking Letters 2
Volume Number:12
Issue Number:9
Column Tag:Getting Started

The Peter Lewis Applet, After

By Dave Mark

Note: Source code files accompanying article are located on MacTech CD-ROM or source code disks.

Last month, we went through the first version of my color blinking text applet. As I told you then, I showed the applet to Peter Lewis (he of Anarchie and other cool Internet software fame) and he rewrote it. This month, we’ll take a look at Peter’s rewrite. As you read through Peter’s code, bear this in mind. This applet definitely is not the only way to do things. Far more importantly, this version of CWBlink introduces a number of important Java topics, all of which you should learn about and eventually master. We’ll aim to cover each topic in more detail in the coming months. For now, just enjoy.

The New CWBlink Project

The new version of CWBlink extends last month’s example with a pushbutton that adds the ability to turn blinking on and off, and also offers a convenient, well-defined place to drop into your debugger. Figure 1 shows CWBlink with color blinking turned on.

The new CWBlink project is based on two Java source files instead of one. The first file, CWBlink.java, contains the heart of the applet, and is divided into two classes. The class CWBlink extends java.applet.Applet, and is the applet itself. The class BlinkingText extends the Canvas class (a generic drawing component class), implements the Runnable interface (which means it can be a thread - see last month’s column), and defines a generic blinking text object. The CWBlink class creates and starts the BlinkingText object.

The second file, AppletFrame.java, is needed only if you want your applet to run standalone, replacing the applet frame with your own frame. This source file is definitely worth understanding. We’ll start off by listing both source code files (along with the associated HTML file), then cover the highlights of each file.

Figure 1. The CWBlink applet with color blinking turned on

If you like the experience of creating your project from scratch (as I do), launch CodeWarrior, create a new project using the Java Applet stationery, then create three new source code files. Here’s the source code for CWBlink.java:

package com.metrowerks.example.CWBlink;

import java.awt.*;

public class CWBlink extends java.applet.Applet
{
 private Button blinkButton;
 private BlinkingText blinkText;

 public String getParameter(String name)
 {
 String result = null;
 
 try
 {
 result = super.getParameter(name);
 }
 catch ( Exception e )
 {
 result = null;
 }
 
 return result;
 }

 public void init()
 {
 Panel tempPanel;
 
 String att = getParameter("speed");
 int speed = (att == null) ?
 500 : (1000 / Integer.valueOf(att).intValue());
 
 setLayout( new BorderLayout() );

 att = getParameter("blinker");
 String blinkString = (att == null) ?
 "CodeWarrior!!!" : att;
 
 blinkButton = new Button( "Blink" );
 
 tempPanel = new Panel();
 tempPanel.add( blinkButton );
 this.add( "North", tempPanel );
 
 blinkText = new BlinkingText( blinkString, speed );
 
 tempPanel = new Panel();
 tempPanel.add( blinkText );
 this.add( "Center", tempPanel );
 
 resize( 570, 170 );
 }
 
 public void start()
 {
 blinkText.start();
 }
 
 public void stop()
 {
 blinkText.stop();
 }
 
 public boolean action(Event evt, Object arg)
 {
 if ( "Blink".equals(arg) )
 {
 blinkText.ToggleBlinking();
 }
 return true;
 }
 
 public static void main(String args[])
 {
 com.metrowerks.AppletFrame.startApplet(
 "com.metrowerks.example.CWBlink.CWBlink",
 "Blink", args);
 }
}


class BlinkingText extends Canvas implements Runnable
{
 private Thread blinkThread = null;
 private String blinkString;
 private Font font;
 private int speed;
 private boolean isBlinking = false;
 private Color[] letters;
 private boolean[] is_black;
 private int current_letter = 0;
 private int old_width, old_height;
 
 private Color RandomColor()
 {
 int red, green, blue;
 
 do {
 red = (int)(Math.random() * 256);
 } while ( red > 0x8000 );
 
 do {
 green = (int)(Math.random() * 256);
 } while ( green > 0x8000 );
 
 do {
 blue = (int)(Math.random() * 256);
 } while ( blue > 0x8000 );
 
 return new java.awt.Color( red, green, blue );
 }
 
 public BlinkingText( String blinkString, int speed )
 {
 this.blinkString = blinkString;
 this.speed = speed / blinkString.length();
 this.font = new java.awt.Font( "TimesRoman",
 Font.PLAIN, 64 );
 this.letters = new Color[blinkString.length()];
 this.is_black = new boolean[blinkString.length()];
 
 for ( int i = 0; i < letters.length; i++ )
 {
 letters[i] = RandomColor();
 is_black[i] = true;
 }
 resize( 530, 70 );
 repaint();
 }
 
 public synchronized void ToggleBlinking()
 {
 isBlinking = ! isBlinking;
 notify();
 }
 
 public synchronized void PaintLetter( int the_letter )
 {
 Rectangle b = bounds();
 int width = b.width;
 int height = b.height;
 Graphics g = getGraphics();
 
 if ( old_width == width && old_height == height )
 {
 int x = 0;
 int y = height;

 g.setFont(font);
 FontMetrics fm = g.getFontMetrics();
 
 for (int index=0; index<the_letter; index++ )
 {
 int w = fm.charWidth(blinkString.charAt(index));
 x += w;
 }
 
 int w = fm.charWidth(blinkString.charAt(the_letter));
 g.setColor( isBlinking ? 
 letters[the_letter] : Color.black );
 g.clearRect( x, 0, w, height );
 g.drawString( blinkString.substring( 
 the_letter,the_letter+1), x, y );

 is_black[the_letter] = !isBlinking;
 }
 else
 {
 paint( g );
 }
 }
 
 public synchronized void paint(Graphics g)
 {
 Rectangle b = bounds();
 int width = b.width;
 int height = b.height;
 old_width = width;
 old_height = height;
 int x = 0;
 int y = height;

 g.setColor(Color.black);
 g.setFont(font);
 FontMetrics fm = g.getFontMetrics();
 
 g.clearRect( 0, 0, width, height );
 if ( isBlinking )
 {
 for (int index=0; index<blinkString.length();
 index++ )
 {
 int w = fm.charWidth(blinkString.charAt(index));
 
 g.setColor( letters[index] );
 
 g.drawString(
 blinkString.substring(index,index+1), x, y);
 x += w;
 }
 }
 else
 {
 g.drawString(blinkString, x, y );
 }
 
 for ( int index=0; index<blinkString.length(); index++ )
 {
 is_black[index] = !isBlinking;
 }
 }

 public void start()
 {
 stop();
 blinkThread = new Thread(this);
 blinkThread.start();
 }
 
 public void stop()
 {
 if ( blinkThread != null )
 {
 blinkThread.stop();
 blinkThread = null;
 }
 }
 
 public void run()
 {
 while (true)
 {
 synchronized ( this )
 {
 try
 {
 wait( 1 );
 }
 catch (Exception e)
 {
 }
 
 if ( isBlinking || !is_black[current_letter] )
 {
 if ( isBlinking )
 {
 letters[current_letter] = RandomColor();
 }
 PaintLetter( current_letter );
 }
 current_letter++;
 if ( current_letter >= blinkString.length() )
 {
 current_letter = 0;
 }
 }
 }
 }
 
 public void finalize()
 {
 stop();
 }
}

Save the source code as CWBlink.java and add it to the project. Next up, here’s the code for AppleFrame.java:

package com.metrowerks;

import java.awt.*;
import java.applet.Applet;

public class AppletFrame extends Frame
{
 public static void startApplet( String className,
 String title, String args[])
 {
 Applet a;
 Dimension appletSize;

 try {
 a = (Applet)
 Class.forName(className).newInstance();
 } catch (ClassNotFoundException e) {
 return;
 } catch (InstantiationException e) {
 return;
 } catch (IllegalAccessException e) {
 return;
 }

 a.init();
 a.start();
 
 AppletFrame f = new AppletFrame(title);
 
 f.add("Center", a);
 
 appletSize =  a.size();
 f.pack();
 f.resize(appletSize);
 f.show();
 
 }

 public AppletFrame(String name)
 {
 super(name);
 }

 public boolean handleEvent(Event e)
 {
 if (e.id == Event.WINDOW_DESTROY)
 {
 dispose();
 return true;
 }
 
 return super.handleEvent(e);
 }
}

Save this code as AppleFrame.java and add it to the project as well. OK, last file. It’s the HTML file:

<title>Blinking CodeWarrior</title>
<hr>
<applet codebase=CWBlink
 code="com/metrowerks/example/CWBlink/CWBlink.class" 
 width=530 
 height=120>
 <param name=blinker value="CodeWarrior!!!">
 <param name=speed value=2>
</applet>
<hr>
<a href="CWBlink.java">The source.</a>

Save this one as CWBlink.html and add it to the project as well. (You don’t have to add the HTML file to the project, but it does make editing the file more convenient - you just double-click on the file name in the project window.)

Once your source code and HTML files are entered and added to the project, go to the Preferences panel, Java Project pane, select Class Folder from the Project Type popup, and enter CWBlink in the Folder Name field. This will store any class files generated by this project in a folder hierarchy inside a folder named CWBlink. This option works well if you plan on serving your applet on a Web page.

Select Make from the Project menu. CodeWarrior will compile your Java code and generate the appropriate .class files. To run your applet, drag your HTML file onto the Metrowerks Java application. If you want to use the debugger, be sure the debugger is enabled and that you have the MetroNub extension installed, then drag the .class files you want to debug onto the MW Debug application. When the debugger launches, click on your source code file name in the debugger window. If your source code file is not in the same folder as the .class file, you’ll be prompted to locate the source file. This can be a hassle, so to prevent it from happening you might want to keep your source files in the same folder as your .class files, even though this is a slight pain to set up.

Once the debugger finds your source code, it lets you do all the normal pre-running things like setting breakpoints. Note that the debugger window for one class will let you set breakpoints only in the functions that belong to that class.

Try this one: Drag CWBlink.class onto the MW Debug application. In the debug window that appears, click on CWBlink.java. When the source code appears, scroll down to this function:

 public boolean action(Event evt, Object arg)
 {
 if ( "Blink".equals(arg) )
 {
 blinkText.ToggleBlinking();
 }
 return true;
 }

Set a breakpoint next to the call to blinkText.ToggleBlinking(). Now go back to the Finder and drag the HTML file onto the Metrowerks Java application. When the applet starts running, click on the Blink button. If all was set up properly, you’ll pop into the debugger at the breakpoint.

Source Code Highlights

Normally, this is where I’d step through every single line of code in the applet. But since you’ve seen a lot of this code before (last month’s column), I’ll just run through the highlights. If you don’t get something about the code, don’t worry. The important thing to take away from this month’s column is list of concepts to read up on.

Take a look at the beginning of CWBlink.java:

package com.metrowerks.example.CWBlink;

import java.awt.*;

The first thing you notice is the package statement. Packages are like C and C++ libraries. The package statement at the beginning of a Java source file gives the collection of classes in this file a name. In this case, the CWBlink and BlinkingText classes are grouped in the package com.metrowerks.example.CWBlink. It’s important that you place the .class files generated from this source file into a directory structure that matches the package name. In this case, the two files CWBlink.class and BlinkingText.class must be placed in a folder with the path com:metrowerks:example:
CWBlink. Fortunately, CodeWarrior does this for you automatically.

You’ve already seen how to access a package: use the import command. In this file, we import the java.awt package.

Note that the getParameter() code was pulled into its own method. Smart move. Gee, why didn’t I think of that?

The init() method has some important new stuff in it. First, notice the use of the Panel class. A Panel is sort of like a PowerPlant View. Java uses the concept of containers and components. A container is just like it sounds, a containing view. A component is an interface element, like a pushbutton or checkbox. A Frame is an applet’s outermost container. A Panel might contain components and other containing classes.

To simplify things, think of a Frame as a Window, and a Panel as a collection of elements you want to group together. If your applet runs in a Web browser, the outer Frame is created for you. If you plan to run the applet standalone, you’ll need to create the Frame yourself. More on that in a minute (when we discuss AppletFrame.java).

The init() method loads the speed parameter (see last month’s column), then sets a layout for the current Frame. You should read up on layouts (any Java book worth its salt will cover them), but here’s the basics.

Every container has a layout that defines how contained elements are to be arranged. For example, the BorderLayout (see java.awt.BorderLayout.html) lays out a container using members named "North", "South", "East", "West" and "Center". A component added as "North" gets placed at the top of the container. A component added as "Center" gets the space left over when the other components are laid out.

Once the init() method sets the layout, it gets the blinking text parameter, then creates a pushbutton with the text "Blink". The button is added to a panel and the panel added to the current container. Since "North" is used, the button will appear at the top of the container.

Next, a new BlinkingText object is created and added to the center of the container. Finally, the container is resized. Play with this stuff. Try using "South" or "East". Change the parameters passed to resize.

Another important CWBlink method is main(). You can actually delete this method, and remove the AppletFrame.java file from your project, if you only want to run the applet from a Web page (from within a pre-built applet Frame). If you want your applet to run standalone, though, you’ll need to build an applet Frame yourself. AppletFrame.java does this. When you are running standalone, main() will get called automatically, and the AppletFrame.startApplet() method will get called.

To learn how all this works, read through the source in AppletFrame.java. It’s not very long, and will serve as a nice introduction to Frames. Even better, you can just add the AppletFrame.java file to your own applet projects.

Finally, the BlinkingText class demonstrates the extremely important topic of threads. As you know, Java is multi-threaded. For example, there is a garbage-collecting thread that ensures that an object that is no longer referenced is deallocated, so that your Java heap won’t end up hopelessly fragmented. The Thread class is very important. Read up on it (check out java.lang.Thread.html). Think of a Thread as a separate little flow of control within your main process.

There are several ways to create a Thread. You can subclass Thread and override the necessary methods (such as run()). Alternatively, you can implement the Runnable interface, which is what BlinkingText does. Once you start a thread, the VM keeps running your threads until they all die.

The synchronized keyword marks a block of code so that only one thread can access it at a time. This means that if one thread starts executing a synchronized method, any other thread that wants to run the same method has to wait until the first method is finished. This keeps two threads from confusing each other - by messing with the same variables, for example.

Till Next Month

We intend to dig into all of these topics in detail in future columns. In the meantime, spend some time with the Java HTML docs and read a good Java book.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Dropbox 193.4.5594 - Cloud backup and sy...
Dropbox is a file hosting service that provides cloud storage, file synchronization, personal cloud, and client software. It is a modern workspace that allows you to get to all of your files, manage... Read more
Google Chrome 122.0.6261.57 - Modern and...
Google Chrome is a Web browser by Google, created to be a modern platform for Web pages and applications. It utilizes very fast loading of Web pages and has a V8 engine, which is a custom built... Read more
Skype 8.113.0.210 - Voice-over-internet...
Skype is a telecommunications app that provides HD video calls, instant messaging, calling to any phone number or landline, and Skype for Business for productive cooperation on the projects. This... Read more
Tor Browser 13.0.10 - Anonymize Web brow...
Using Tor Browser you can protect yourself against tracking, surveillance, and censorship. Tor was originally designed, implemented, and deployed as a third-generation onion-routing project of the U.... Read more
Deeper 3.0.4 - Enable hidden features in...
Deeper is a personalization utility for macOS which allows you to enable and disable the hidden functions of the Finder, Dock, QuickTime, Safari, iTunes, login window, Spotlight, and many of Apple's... Read more
OnyX 4.5.5 - Maintenance and optimizatio...
OnyX is a multifunction utility that you can use to verify the startup disk and the structure of its system files, to run miscellaneous maintenance and cleaning tasks, to configure parameters in the... Read more
Hopper Disassembler 5.14.1 - Binary disa...
Hopper Disassembler is a binary disassembler, decompiler, and debugger for 32- and 64-bit executables. It will let you disassemble any binary you want, and provide you all the information about its... Read more

Latest Forum Discussions

See All

Zenless Zone Zero opens entries for its...
miHoYo, aka HoYoverse, has become such a big name in mobile gaming that it's hard to believe that arguably their flagship title, Genshin Impact, is only three and a half years old. Now, they continue the road to the next title in their world, with... | Read more »
Live, Playdate, Live! – The TouchArcade...
In this week’s episode of The TouchArcade Show we kick things off by talking about all the games I splurged on during the recent Playdate Catalog one-year anniversary sale, including the new Lucas Pope jam Mars After Midnight. We haven’t played any... | Read more »
TouchArcade Game of the Week: ‘Vroomies’
So here’s a thing: Vroomies from developer Alex Taber aka Unordered Games is the Game of the Week! Except… Vroomies came out an entire month ago. It wasn’t on my radar until this week, which is why I included it in our weekly new games round-up, but... | Read more »
SwitchArcade Round-Up: ‘MLB The Show 24’...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for March 15th, 2024. We’re closing out the week with a bunch of new games, with Sony’s baseball franchise MLB The Show up to bat yet again. There are several other interesting games to... | Read more »
Steam Deck Weekly: WWE 2K24 and Summerho...
Welcome to this week’s edition of the Steam Deck Weekly. The busy season has begun with games we’ve been looking forward to playing including Dragon’s Dogma 2, Horizon Forbidden West Complete Edition, and also console exclusives like Rise of the... | Read more »
Steam Spring Sale 2024 – The 10 Best Ste...
The Steam Spring Sale 2024 began last night, and while it isn’t as big of a deal as say the Steam Winter Sale, you may as well take advantage of it to save money on some games you were planning to buy. I obviously recommend checking out your own... | Read more »
New ‘SaGa Emerald Beyond’ Gameplay Showc...
Last month, Square Enix posted a Let’s Play video featuring SaGa Localization Director Neil Broadley who showcased the worlds, companions, and more from the upcoming and highly-anticipated RPG SaGa Emerald Beyond. | Read more »
Choose Your Side in the Latest ‘Marvel S...
Last month, Marvel Snap (Free) held its very first “imbalance" event in honor of Valentine’s Day. For a limited time, certain well-known couples were given special boosts when conditions were right. It must have gone over well, because we’ve got a... | Read more »
Warframe welcomes the arrival of a new s...
As a Warframe player one of the best things about it launching on iOS, despite it being arguably the best way to play the game if you have a controller, is that I can now be paid to talk about it. To whit, we are gearing up to receive the first... | Read more »
Apple Arcade Weekly Round-Up: Updates an...
Following the new releases earlier in the month and April 2024’s games being revealed by Apple, this week has seen some notable game updates and events go live for Apple Arcade. What The Golf? has an April Fool’s Day celebration event going live “... | Read more »

Price Scanner via MacPrices.net

Apple Education is offering $100 discounts on...
If you’re a student, teacher, or staff member at any educational institution, you can use your .edu email address when ordering at Apple Education to take $100 off the price of a new M3 MacBook Air.... Read more
Apple Watch Ultra 2 with Blood Oxygen feature...
Best Buy is offering Apple Watch Ultra 2 models for $50 off MSRP on their online store this week. Sale prices available for online orders only, in-store prices may vary. Order online, and choose... Read more
New promo at Sams Club: Apple HomePods for $2...
Sams Club has Apple HomePods on sale for $259 through March 31, 2024. Their price is $40 off Apple’s MSRP, and both Space Gray and White colors are available. Sale price is for online orders only, in... Read more
Get Apple’s 2nd generation Apple Pencil for $...
Apple’s Pencil (2nd generation) works with the 12″ iPad Pro (3rd, 4th, 5th, and 6th generation), 11″ iPad Pro (1st, 2nd, 3rd, and 4th generation), iPad Air (4th and 5th generation), and iPad mini (... Read more
10th generation Apple iPads on sale for $100...
Best Buy has Apple’s 10th-generation WiFi iPads back on sale for $100 off MSRP on their online store, starting at only $349. With the discount, Best Buy’s prices are the lowest currently available... Read more
iPad Airs on sale again starting at $449 on B...
Best Buy has 10.9″ M1 WiFi iPad Airs on record-low sale prices again for $150 off Apple’s MSRP, starting at $449. Sale prices for online orders only, in-store price may vary. Order online, and choose... Read more
Best Buy is blowing out clearance 13-inch M1...
Best Buy is blowing out clearance Apple 13″ M1 MacBook Airs this weekend for only $649.99, or $350 off Apple’s original MSRP. Sale prices for online orders only, in-store prices may vary. Order... Read more
Low price alert! You can now get a 13-inch M1...
Walmart has, for the first time, begun offering new Apple MacBooks for sale on their online store, albeit clearance previous-generation models. They now have the 13″ M1 MacBook Air (8GB RAM, 256GB... Read more
Best Apple MacBook deal this weekend: Get the...
Apple has 13″ M2 MacBook Airs available for only $849 today in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty is included,... Read more
New 15-inch M3 MacBook Air (Midnight) on sale...
Amazon has the new 15″ M3 MacBook Air (8GB RAM/256GB SSD/Midnight) in stock and on sale today for $1249.99 including free shipping. Their price is $50 off MSRP, and it’s the lowest price currently... Read more

Jobs Board

Early Preschool Teacher - Glenda Drive/ *Appl...
Early Preschool Teacher - Glenda Drive/ Apple ValleyTeacher Share by Email Share on LinkedIn Share on Twitter Read more
Senior Software Engineer - *Apple* Fundamen...
…center of Microsoft's efforts to empower our users to do more. The Apple Fundamentals team focused on defining and improving the end-to-end developer experience in Read more
Relationship Banker *Apple* Valley Main - W...
…Alcohol Policy to learn more. **Company:** WELLS FARGO BANK **Req Number:** R-350696 **Updated:** Mon Mar 11 00:00:00 UTC 2024 **Location:** APPLE VALLEY,California Read more
Medical Assistant - Surgical Oncology- *Apple...
Medical Assistant - Surgical Oncology- Apple Hill WellSpan Medical Group, York, PA | Nursing | Nursing Support | FTE: 1 | Regular | Tracking Code: 200555 Apply Now Read more
Early Preschool Teacher - Glenda Drive/ *Appl...
Early Preschool Teacher - Glenda Drive/ Apple ValleyTeacher Share by Email Share on LinkedIn Share on Twitter Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.