TweetFollow Us on Twitter

Java Events
Volume Number:12
Issue Number:12
Column Tag:Getting Started

Java Events

By Dave Mark

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

Originally I was planning to cover double-buffering in this month’s column. I started writing a cool banner animator, then I got a little side-tracked playing with Java’s event-handling mechanism. As I explored (and as my animation applet took on a life of its own!), I realized that we never really covered events. Since events are the heart and soul of your applet’s user interaction, and since I ended up writing this nifty little event doodad anyway, I thought we would dive into events now and put off animation for the moment.

The Ultimate Event Handler

This month’s applet is called eventHandler. For you Primer readers, eventHandler is similar to eventTracker. As you click, drag, and type, the events associated with those actions are displayed in a scrolling list. Figure 1 shows eventHandler running in the Metrowerks Java applet viewer. One thing I learned from this exercise is that no two applet viewers behave exactly the same way. For example, the Metrowerks Java viewer swallows keyUp events. In Netscape Gold 3.0 (see Figure 2), the keyUp events show up, but mouseMove events are not reported properly. The Sun JDK Applet Viewer 1.0.2 (not shown) doesn’t handle clipping correctly. <sigh>. Well, at least these applet viewers are much better than their predecessors!

Figure 1. eventHandler running in Metrowerks’ Applet Viewer. Notice that keyUp events are swallowed. See Figure 2.

Figure 2. eventHandler running in Netscape Gold 3.0. The keyUp events are there, but mouseMove events (not shown) don’t work right.

eventHandler consists of two major areas (each with its own label). On the top is a Canvas with a yellow background. All the events trapped by this Canvas are listed in the scrolling TextArea on the bottom. When the keyboard focus is on the Canvas, its border is drawn in red. When the Canvas loses the keyboard focus, the border is redrawn as yellow.

If you click or drag in the Canvas, the appropriate events get listed in the scrolling list. If you type while the focus is in the Canvas, the actual key names are listed when the keyDown event is reported. Note that I don’t report the mouseMove event, which is supposed to occur when you move the mouse. Unfortunately, the Metrowerks viewer is the only one that handles this correctly. Both Netscape and the Sun viewer report a steady stream of mouseMove events, even when the mouse is perfectly still! This can be a real pain, since any other events tend to get swept away in a flood of incorrectly reported mouseMove events. Add a mouseMove handler to the code below, just to see this for yourself.

The eventHandler Source Code

Create a new project using the Java Applet stationery. Create a source code file named eventHandler.java and add it to the project. Here’s the source code:

import java.awt.*;

public class eventCanvas extends Canvas
{
 booleanhasFocus;
 
 eventCanvas( int width, int height )
 {
 setBackground( Color.yellow );
 resize( width, height );
 
 hasFocus = false;
 }
 
 public boolean mouseUp( Event e, int x, int y )
 {
 eventHandler.reportEvent( “mouseUp” );
 return true;
 }
 
 public boolean mouseDown( Event e, int x, int y )
 {
 eventHandler.reportEvent( “mouseDown” );
 return true;
 }
 
 public boolean mouseDrag( Event e, int x, int y )
 {
 eventHandler.reportEvent( “mouseDrag” );
 return true;
 }
 
 public boolean mouseEnter( Event e, int x, int y )
 {
 eventHandler.reportEvent( “mouseEnter” );
 return true;
 }
 
 public boolean mouseExit( Event e, int x, int y )
 {
 eventHandler.reportEvent( “mouseExit” );
 return true;
 }
 
 public boolean keyDown( Event e, int key )
 {
 String eventString = “keyDown: “;
 String keyName, modifierName;
 
 modifierName = getModifierName( e );
 if ( modifierName != null )
 eventString += modifierName;
 
 keyName = getKeyName( key );
 
 if ( keyName != null )
 eventString += keyName;
 else if (( key >= 32 ) && ( key <= 127 ))
 eventString += new Character( (char)key ).toString();
 else
 eventString += key;
 
 eventHandler.reportEvent( eventString );
 
 return true;
 }
 
 public String getModifierName( Event e )
 {
 if ( e.controlDown() )
 return( “Control-” );
 if ( e.metaDown() )
 return( “Meta-” );
 if ( e.shiftDown() )
 return( “Shift-” );
 
 return null;
 }
 
 public String getKeyName( int key )
 {
 switch ( key )
 {
 case Event.F1: return “F1”;
 case Event.F2: return “F2”;
 case Event.F3: return “F3”;
 case Event.F4: return “F4”;
 case Event.F5: return “F5”;
 case Event.F6: return “F6”;
 case Event.F7: return “F7”;
 case Event.F8: return “F8”;
 case Event.F9: return “F9”;
 case Event.F10: return “F10”;
 case Event.F11: return “F11”;
 case Event.F12: return “F12”;
 case Event.HOME: return “HOME”;
 case Event.END: return “END”;
 case Event.LEFT: return “Left Arrow”;
 case Event.RIGHT: return “Right Arrow”;
 case Event.UP: return “Up Arrow”;
 case Event.DOWN: return “DownArrow”;
 case Event.PGUP: return “Page Up”;
 case Event.PGDN: return “Page Down”;
 }
 
 return null;
 }
 
 public boolean keyUp( Event e, int key )
 {
 eventHandler.reportEvent( “keyUp” );
 
 return true;
 }
 
 public boolean gotFocus(Event e, Object what)
 {
 hasFocus = true;
 eventHandler.reportEvent( “gotFocus” );
 repaint();
 
 return true;
 }
 
 public boolean lostFocus(Event e, Object what)
 {
 hasFocus = false;
 eventHandler.reportEvent( “lostFocus” );
 repaint();
 
 return true;
 }
 
 public void paint( Graphics g )
 {
 Rectangler;
 
 r = bounds();
 g = getGraphics();
 
 if ( hasFocus )
 g.setColor( Color.red );
 else
 g.setColor( Color.yellow );
 
 g.drawRect( 0, 0, r.width-1, r.height-1 );
 g.drawRect( 1, 1, r.width-3, r.height-3 );
 }
}

public class eventHandler extends java.applet.Applet
{
 eventCanvaseCanvas;
 static TextArea tArea;
 
 public void init()
 {
 add( new Label( “Click and type in this Canvas:” ) );
 
 eCanvas = new eventCanvas( 200, 100 );
 add( eCanvas );
 
 add( new Label( “Here’s a list of canvas events:” ) );
 
 tArea = new TextArea( 10, 30 );
 add( tArea );
 }
 
 public static void reportEvent( String eventString )
 {
 tArea.appendText( eventString + “\r” );
 }
}

Now create a file named eventHandler.html and add it to the project as well. Here’s the HTML:

<title>Event Handler</title>
<hr>
<applet codebase=”eventHandler Classes” code=”eventHandler.class” width=290 
height=320>
</applet>
<hr>
<a href=”eventHandler.java”>The source.</a>

Now go into the Project Settings dialog (Under CW10, select Project Settings... from the Edit menu. See Figure 3. Earlier versions, Preferences from the Edit menu) and click on Project/Java Project. Select Class Folder from the Project Type popup and type “eventHandler Classes” as the File Name. Note that we’re no longer using non-ASCII characters (like ƒ) in our Java-specific file and folder names. Though some environments can deal with these special characters, other environments, like Netscape, don’t recognize them and won’t be able to locate your class files.

Figure 3. The CW10 Project Settings dialog.

A terrific feature introduced with CW10 (there are a bunch of them) is the Set... button in the Project Settings dialog, which lets you select the application to which your html will be sent when you select Run from the Project menu. So if you like, you can use Netscape to test your applet or, if you prefer, use the applet viewer that ships with the JDK or with CW10. No matter which applet viewer you choose, be aware of any class caching schemes used by the viewer. If the viewer caches your class, it won’t replace the class each time you run with a new version unless you quit the viewer each time you run. As I write this, I don’t know of any work-arounds for this. On the other hand, by the time you read this, maybe this won’t be an issue anymore.

Running eventHandler

Once your source is entered, build your .class file and drop your html file on your favorite viewer. If you are using CodeWarrior, select Run from the Project menu. Once your applet appears, generate some events. Try dragging the mouse within the Canvas to generate a stream of mouseDrag events. Click on the Canvas to generate a gotFocus event, then click outside the Canvas to lose the focus. Click on the Canvas to regain the focus, then bring the Finder to the front. Notice that the focus is lost, then regained when you bring the applet viewer to the front.

Experiment!

The eventHandler Source Code

eventHandler is broken into two classes. The eventCanvas class implements the yellow canvas area, adding to it the various event handlers. The hasFocus variable is a boolean that specifies whether the Canvas currently has the keyboard focus. The constructor takes a width and height, sets the background color to yellow, resizes the Canvas, and sets the focus to false.

import java.awt.*;

public class eventCanvas extends Canvas
{
 booleanhasFocus;
 
 eventCanvas( int width, int height )


 {
 setBackground( Color.yellow );
 resize( width, height );
 
 hasFocus = false;
 }

Each of the event handlers overrides a default Canvas event handler. Each one reports its event by calling the static eventHandler function reportEvent(). We will get to that when we explore the eventHandler class in a bit. Each handler returns true, signifying that it has dealt with the event. mouseUp() and mouseDown() are called when the mouse button is pressed or released within the eventCanvas component.

 public boolean mouseUp( Event e, int x, int y )
 {
 eventHandler.reportEvent( “mouseUp” );
 return true;
 }
 
 public boolean mouseDown( Event e, int x, int y )
 {
 eventHandler.reportEvent( “mouseDown” );
 return true;
 }

mouseDrag() is called when the mouse is dragged within the eventCanvas, and mouseEnter() and mouseExit() are called when the mouse enters or leaves the eventCanvas boundaries.

 public boolean mouseDrag( Event e, int x, int y )
 {
 eventHandler.reportEvent( “mouseDrag” );
 return true;
 }
 
 public boolean mouseEnter( Event e, int x, int y )
 {
 eventHandler.reportEvent( “mouseEnter” );
 return true;
 }
 
 public boolean mouseExit( Event e, int x, int y )
 {
 eventHandler.reportEvent( “mouseExit” );
 return true;
 }

keyDown() is called when a key is pressed, ONLY IF the eventCanvas has the focus. The keyDown() code basically builds a string reflecting the name of the key that was pressed. getModifierName() checks to see if the control, meta, or shift keys were down and, if so, adds the appropriate modifier name to the string. getKeyName() does a lookup on some standard Java key names. This table should be larger, but these are the only keynames I could find in the documentation. For example, I couldn’t find a TAB constant.

If the key was an ASCII between 32 and 127, the character name is used, otherwise the key number is used. keyDown() is very simple-minded. After you experiment with it a bit, you might want to add more complexity to it to handle the other key types.

 public boolean keyDown( Event e, int key )
 {
 String eventString = “keyDown: “;
 String keyName, modifierName;
 
 modifierName = getModifierName( e );
 if ( modifierName != null )
 eventString += modifierName;
 
 keyName = getKeyName( key );
 
 if ( keyName != null )
 eventString += keyName;
 else if (( key >= 32 ) && ( key <= 127 ))
 eventString += new Character( (char)key ).toString();
 else
 eventString += key;
 
 eventHandler.reportEvent( eventString );
 
 return true;
 }
 
 public String getModifierName( Event e )
 {
 if ( e.controlDown() )
 return( “Control-” );
 if ( e.metaDown() )
 return( “Meta-” );
 if ( e.shiftDown() )
 return( “Shift-” );
 
 return null;
 }
 
 public String getKeyName( int key )
 {
 switch ( key )
 {
 case Event.F1: return “F1”;
 case Event.F2: return “F2”;
 case Event.F3: return “F3”;
 case Event.F4: return “F4”;
 case Event.F5: return “F5”;
 case Event.F6: return “F6”;
 case Event.F7: return “F7”;
 case Event.F8: return “F8”;
 case Event.F9: return “F9”;
 case Event.F10: return “F10”;
 case Event.F11: return “F11”;
 case Event.F12: return “F12”;
 case Event.HOME: return “HOME”;
 case Event.END: return “END”;
 case Event.LEFT: return “Left Arrow”;
 case Event.RIGHT: return “Right Arrow”;
 case Event.UP: return “Up Arrow”;
 case Event.DOWN: return “DownArrow”;
 case Event.PGUP: return “Page Up”;
 case Event.PGDN: return “Page Down”;
 }
 
 return null;
 }
 
 public boolean keyUp( Event e, int key )
 {
 eventHandler.reportEvent( “keyUp” );
 
 return true;
 }

gotFocus() sets hasFocus to true, reports the event, and forces a redraw. lostFocus() sets hasFocus to false and does the same.

 public boolean gotFocus(Event e, Object what)
 {
 hasFocus = true;
 eventHandler.reportEvent( “gotFocus” );
 repaint();
 
 return true;
 }
 
 public boolean lostFocus(Event e, Object what)
 {
 hasFocus = false;
 eventHandler.reportEvent( “lostFocus” );
 repaint();
 
 return true;
 }

paint() sets the drawing color to red if the eventCanvas has the focus (yellow otherwise), then draws the bordering rectangle based on the bounding rectangle of the eventCanvas. Another peculiarity I ran into was trying to draw a pair of rectangles, one inside the other. I expected to use r.width-2 and r.height-2 as parameters to the second drawRect call. Somehow this didn’t produce the results I expected. I tried this with all the viewers, and got different results with each one. I’m guessing that this is a flaw in the viewer implementation, though of course that assumption is pretty dangerous! If anyone sees a bug in this code, let me know <dmark@aol.com>.

 public void paint( Graphics g )
 {
 Rectangler;
 
 r = bounds();
 g = getGraphics();
 
 if ( hasFocus )
 g.setColor( Color.red );
 else
 g.setColor( Color.yellow );
 
 g.drawRect( 0, 0, r.width-1, r.height-1 );
 g.drawRect( 1, 1, r.width-3, r.height-3 );
 }
}

The eventHandler class implements the applet itself. The reportEvent() method is static so it can be called from outside the class without having a specific eventHandle object reference. This is one way to solve this problem. There are certainly others. We could have retrieved the current applet from within the eventCanvas class, coerced that reference to an eventCanvas and used it to call reportEvent(). I think the first way is better. Any other ideas? Let me know.

The TextArea variable tArea was also made static so it could be referenced from within the static reportEvent. The disadvantage here is that this approach limits you to single occurances of the applet. Again, I’m definitely interested in hearing any other ideas you might have.

public class eventHandler extends java.applet.Applet
{
 eventCanvaseCanvas;
 static TextArea tArea;
 
 public void init()
 {
 add( new Label( “Click and type in this Canvas:” ) );
 
 eCanvas = new eventCanvas( 200, 100 );
 add( eCanvas );
 
 add( new Label( “Here’s a list of canvas events:” ) );
 
 tArea = new TextArea( 10, 30 );
 add( tArea );
 }
 
 public static void reportEvent( String eventString )
 {
 tArea.appendText( eventString + “\r” );
 }
}

Till Next Month...

This was one of the most interesting applets I’ve worked on, both because of the nature of the problem the applet solved, and because of the many differences between the various applet viewers. Java is still evolving rapidly and the tools will be playing catch-up for a while. Have a very happy holiday season and I look forward to seeing you all in 1997.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Go from lowly lizard to wicked Wyvern in...
Do you like questing, and do you like dragons? If not then boy is this not the announcement for you, as Loongcheer Game has unveiled Quest Dragon: Idle Mobile Game. Yes, it is amazing Square Enix hasn’t sued them for copyright infringement, but... | Read more »
Aether Gazer unveils Chapter 16 of its m...
After a bit of maintenance, Aether Gazer has released Chapter 16 of its main storyline, titled Night Parade of the Beasts. This big update brings a new character, a special outfit, some special limited-time events, and, of course, an engaging... | Read more »
Challenge those pesky wyverns to a dance...
After recently having you do battle against your foes by wildly flailing Hello Kitty and friends at them, GungHo Online has whipped out another surprising collaboration for Puzzle & Dragons. It is now time to beat your opponents by cha-cha... | Read more »
Pack a magnifying glass and practice you...
Somehow it has already been a year since Torchlight: Infinite launched, and XD Games is celebrating by blending in what sounds like a truly fantastic new update. Fans of Cthulhu rejoice, as Whispering Mist brings some horror elements, and tests... | Read more »
Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »

Price Scanner via MacPrices.net

Limited-time sale: 13-inch M3 MacBook Airs fo...
Amazon has the base 13″ M3 MacBook Air (8GB/256GB) in stock and on sale for a limited time for $989 shipped. That’s $110 off MSRP, and it’s the lowest price we’ve seen so far for an M3-powered... Read more
13-inch M2 MacBook Airs in stock today at App...
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 today at Apple: Series 9 Watches availabl...
Apple is now offering Certified Refurbished Apple Watch Series 9 models on their online store for up to $80 off MSRP, starting at $339. Each Watch includes Apple’s standard one-year warranty, a new... Read more
The latest Apple iPhone deals from wireless c...
We’ve updated our iPhone Price Tracker with the latest carrier deals on Apple’s iPhone 15 family of smartphones as well as previous models including the iPhone 14, 13, 12, 11, and SE. Use our price... Read more
Boost Mobile will sell you an iPhone 11 for $...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering an iPhone 11 for $149.99 when purchased with their $40 Unlimited service plan (12GB of premium data). No trade-in is required... Read more
Free iPhone 15 plus Unlimited service for $60...
Boost Infinite, part of MVNO Boost Mobile using AT&T and T-Mobile’s networks, is offering a free 128GB iPhone 15 for $60 per month including their Unlimited service plan (30GB of premium data).... Read more
$300 off any new iPhone with service at Red P...
Red Pocket Mobile has new Apple iPhones on sale for $300 off MSRP when you switch and open up a new line of service. Red Pocket Mobile is a nationwide MVNO using all the major wireless carrier... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, available for $759 for 8-Core CPU/7-Core GPU/256GB models and $929 for 8-Core CPU/8-Core GPU/512GB models. Apple’s one-year warranty is... Read more
Updated Apple MacBook Price Trackers
Our Apple award-winning MacBook Price Trackers are continually updated with the latest information on prices, bundles, and availability for 16″ and 14″ MacBook Pros along with 13″ and 15″ MacBook... Read more
Every model of Apple’s 13-inch M3 MacBook Air...
Best Buy has Apple 13″ MacBook Airs with M3 CPUs in stock and on sale today for $100 off MSRP. Prices start at $999. Their prices are the lowest currently available for new 13″ M3 MacBook Airs among... Read more

Jobs Board

Solutions Engineer - *Apple* - SHI (United...
**Job Summary** An Apple Solution Engineer's primary role is tosupport SHI customers in their efforts to select, deploy, and manage Apple operating systems and Read more
DMR Technician - *Apple* /iOS Systems - Haml...
…relevant point-of-need technology self-help aids are available as appropriate. ** Apple Systems Administration** **:** Develops solutions for supporting, deploying, Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.