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

Fresh From the Land Down Under – The Tou...
After a two week hiatus, we are back with another episode of The TouchArcade Show. Eli is fresh off his trip to Australia, which according to him is very similar to America but more upside down. Also kangaroos all over. Other topics this week... | Read more »
TouchArcade Game of the Week: ‘Dungeon T...
I’m a little conflicted on this week’s pick. Pretty much everyone knows the legend of Dungeon Raid, the match-3 RPG hybrid that took the world by storm way back in 2011. Everyone at the time was obsessed with it, but for whatever reason the... | Read more »
SwitchArcade Round-Up: Reviews Featuring...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for July 19th, 2024. In today’s article, we finish up the week with the unusual appearance of a review. I’ve spent my time with Hot Lap Racing, and I’m ready to give my verdict. After... | Read more »
Draknek Interview: Alan Hazelden on Thin...
Ever since I played my first release from Draknek & Friends years ago, I knew I wanted to sit down with Alan Hazelden and chat about the team, puzzle games, and much more. | Read more »
The Latest ‘Marvel Snap’ OTA Update Buff...
I don’t know about all of you, my fellow Marvel Snap (Free) players, but these days when I see a balance update I find myself clenching my… teeth and bracing for the impact to my decks. They’ve been pretty spicy of late, after all. How will the... | Read more »
‘Honkai Star Rail’ Version 2.4 “Finest D...
HoYoverse just announced the Honkai Star Rail (Free) version 2.4 “Finest Duel Under the Pristine Blue" update alongside a surprising collaboration. Honkai Star Rail 2.4 follows the 2.3 “Farewell, Penacony" update. Read about that here. | Read more »
‘Vampire Survivors+’ on Apple Arcade Wil...
Earlier this month, Apple revealed that poncle’s excellent Vampire Survivors+ () would be heading to Apple Arcade as a new App Store Great. I reached out to poncle to check in on the DLC for Vampire Survivors+ because only the first two DLCs were... | Read more »
Homerun Clash 2: Legends Derby opens for...
Since launching in 2018, Homerun Clash has performed admirably for HAEGIN, racking up 12 million players all eager to prove they could be the next baseball champions. Well, the title will soon be up for grabs again, as Homerun Clash 2: Legends... | Read more »
‘Neverness to Everness’ Is a Free To Pla...
Perfect World Games and Hotta Studio (Tower of Fantasy) announced a new free to play open world RPG in the form of Neverness to Everness a few days ago (via Gematsu). Neverness to Everness has an urban setting, and the two reveal trailers for it... | Read more »
Meditative Puzzler ‘Ouros’ Coming to iOS...
Ouros is a mediative puzzle game from developer Michael Kamm that launched on PC just a couple of months back, and today it has been revealed that the title is now heading to iOS and Android devices next month. Which is good news I say because this... | Read more »

Price Scanner via MacPrices.net

Amazon is still selling 16-inch MacBook Pros...
Prime Day in July is over, but Amazon is still selling 16-inch Apple MacBook Pros for $500-$600 off MSRP. Shipping is free. These are the lowest prices available this weekend for new 16″ Apple... Read more
Walmart continues to sell clearance 13-inch M...
Walmart continues to offer clearance, but new, Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBooks... Read more
Apple is offering steep discounts, up to $600...
Apple has standard-configuration 16″ M3 Max MacBook Pros available, Certified Refurbished, starting at $2969 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free,... Read more
Save up to $480 with these 14-inch M3 Pro/M3...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
Amazon has clearance 9th-generation WiFi iPad...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80-$100 off MSRP, starting only $249. Their prices are the lowest available for new iPads anywhere: – 10″ 64GB WiFi iPad (Space Gray or... Read more
Apple is offering a $50 discount on 2nd-gener...
Apple has Certified Refurbished White and Midnight HomePods available for $249, Certified Refurbished. That’s $50 off MSRP and the lowest price currently available for a full-size Apple HomePod today... Read more
The latest MacBook Pro sale at Amazon: 16-inc...
Amazon is offering instant discounts on 16″ M3 Pro and 16″ M3 Max MacBook Pros ranging up to $400 off MSRP as part of their early July 4th sale. Shipping is free. These are the lowest prices... Read more
14-inch M3 Pro MacBook Pros with 36GB of RAM...
B&H Photo has 14″ M3 Pro MacBook Pros with 36GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 Pro MacBook Pro (... Read more
14-inch M3 MacBook Pros with 16GB of RAM on s...
B&H Photo has 14″ M3 MacBook Pros with 16GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $150-$200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 MacBook Pro (... Read more
Amazon is offering $170-$200 discounts on new...
Amazon is offering a $170-$200 discount on every configuration and color of Apple’s M3-powered 15″ MacBook Airs. Prices start at $1129 for models with 8GB of RAM and 256GB of storage: – 15″ M3... Read more

Jobs Board

*Apple* Systems Engineer - Chenega Corporati...
…LLC,** a **Chenega Professional Services** ' company, is looking for a ** Apple Systems Engineer** to support the Information Technology Operations and Maintenance Read more
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
*Apple* / Mac Administrator - JAMF Pro - Ame...
Amentum is seeking an ** Apple / Mac Administrator - JAMF Pro** to provide support with the Apple Ecosystem to include hardware and software to join our team and 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.