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

Fallout Shelter pulls in ten times its u...
When the Fallout TV series was announced I, like I assume many others, assumed it was going to be an utter pile of garbage. Well, as we now know that couldn't be further from the truth. It was a smash hit, and this success has of course given the... | Read more »
Recruit two powerful-sounding students t...
I am a fan of anime, and I hear about a lot that comes through, but one that escaped my attention until now is A Certain Scientific Railgun T, and that name is very enticing. If it's new to you too, then players of Blue Archive can get a hands-on... | Read more »
Top Hat Studios unveils a new gameplay t...
There are a lot of big games coming that you might be excited about, but one of those I am most interested in is Athenian Rhapsody because it looks delightfully silly. The developers behind this project, the rather fancy-sounding Top Hat Studios,... | Read more »
Bound through time on the hunt for sneak...
Have you ever sat down and wondered what would happen if Dr Who and Sherlock Holmes went on an adventure? Well, besides probably being the best mash-up of English fiction, you'd get the Hidden Through Time series, and now Rogueside has announced... | Read more »
The secrets of Penacony might soon come...
Version 2.2 of Honkai: Star Rail is on the horizon and brings the culmination of the Penacony adventure after quite the escalation in the latest story quests. To help you through this new expansion is the introduction of two powerful new... | Read more »
The Legend of Heroes: Trails of Cold Ste...
I adore game series that have connecting lore and stories, which of course means the Legend of Heroes is very dear to me, Trails lore has been building for two decades. Excitedly, the next stage is upon us as Userjoy has announced the upcoming... | Read more »
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 »

Price Scanner via MacPrices.net

Verizon has Apple AirPods on sale this weeken...
Verizon has Apple AirPods on sale for up to 31% off MSRP on their online store this weekend. Their prices are the lowest price available for AirPods from any Apple retailer. Verizon service is not... Read more
Apple has 15-inch M2 MacBook Airs available s...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs available starting at $1019 and ranging up to $300 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at Apple.... Read more
May 2024 Apple Education discounts on MacBook...
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 up to $300 off the purchase of a new MacBook... Read more
Clearance 16-inch M2 Pro MacBook Pros in stoc...
Apple has clearance 16″ M2 Pro MacBook Pros available in their Certified Refurbished store starting at $2049 and ranging up to $450 off original MSRP. Each model features a new outer case, shipping... Read more
Save $300 at Apple on 14-inch M3 MacBook Pros...
Apple has 14″ M3 MacBook Pros with 16GB of RAM, Certified Refurbished, available for $270-$300 off MSRP. Each model features a new outer case, shipping is free, and an Apple 1-year warranty is... Read more
Apple continues to offer 14-inch M3 MacBook P...
Apple has 14″ M3 MacBook Pros, Certified Refurbished, available starting at only $1359 and ranging up to $270 off MSRP. Each model features a new outer case, shipping is free, and an Apple 1-year... Read more
Apple AirPods Pro with USB-C return to all-ti...
Amazon has Apple’s AirPods Pro with USB-C in stock and on sale for $179.99 including free shipping. Their price is $70 (28%) off MSRP, and it’s currently the lowest price available for new AirPods... Read more
Apple Magic Keyboards for iPads are on sale f...
Amazon has Apple Magic Keyboards for iPads on sale today for up to $70 off MSRP, shipping included: – Magic Keyboard for 10th-generation Apple iPad: $199, save $50 – Magic Keyboard for 11″ iPad Pro/... Read more
Apple’s 13-inch M2 MacBook Airs return to rec...
Apple retailers have 13″ MacBook Airs with M2 CPUs in stock and on sale this weekend starting at only $849 in Space Gray, Silver, Starlight, and Midnight colors. These are the lowest prices currently... Read more
Best Buy is clearing out iPad Airs for up to...
In advance of next week’s probably release of new and updated iPad Airs, Best Buy has 10.9″ M1 WiFi iPad Airs on record-low sale prices for up to $200 off Apple’s MSRP, starting at $399. Sale prices... Read more

Jobs Board

Liquor Stock Clerk - S. *Apple* St. - Idaho...
Liquor Stock Clerk - S. Apple St. Boise Posting Begin Date: 2023/10/10 Posting End Date: 2024/10/14 Category: Retail Sub Category: Customer Service Work Type: Part Read more
*Apple* App Developer - Datrose (United Stat...
…year experiencein programming and have computer knowledge with SWIFT. Job Responsibilites: Apple App Developer is expected to support essential tasks for the RxASL 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.