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

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.