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

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 »
MoreFun Studios has announced Season 4,...
Tension has escalated in the ever-volatile world of Arena Breakout, as your old pal Randall Fisher and bosses Fred and Perrero continue to lob insults and explosives at each other, bringing us to a new phase of warfare. Season 4, Into The Fog of... | Read more »
Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links below... | Read more »
Marvel Future Fight celebrates nine year...
Announced alongside an advertising image I can only assume was aimed squarely at myself with the prominent Deadpool and Odin featured on it, Netmarble has revealed their celebrations for the 9th anniversary of Marvel Future Fight. The Countdown... | Read more »
HoYoFair 2024 prepares to showcase over...
To say Genshin Impact took the world by storm when it was released would be an understatement. However, I think the most surprising part of the launch was just how much further it went than gaming. There have been concerts, art shows, massive... | Read more »

Price Scanner via MacPrices.net

Apple Watch Ultra 2 now available at Apple fo...
Apple has, for the first time, begun offering Certified Refurbished Apple Watch Ultra 2 models in their online store for $679, or $120 off MSRP. Each Watch includes Apple’s standard one-year warranty... Read more
AT&T has the iPhone 14 on sale for only $...
AT&T has the 128GB Apple iPhone 14 available for only $5.99 per month for new and existing customers when you activate unlimited service and use AT&T’s 36 month installment plan. The fine... Read more
Amazon is offering a $100 discount on every M...
Amazon is offering a $100 instant discount on each configuration of Apple’s new 13″ M3 MacBook Air, in Midnight, this weekend. These are the lowest prices currently available for new 13″ M3 MacBook... Read more
You can save $300-$480 on a 14-inch M3 Pro/Ma...
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
24-inch M1 iMacs available at Apple starting...
Apple has clearance M1 iMacs available in their Certified Refurbished store starting at $1049 and ranging up to $300 off original MSRP. Each iMac is in like-new condition and comes with Apple’s... Read more
Walmart continues to offer $699 13-inch M1 Ma...
Walmart continues to offer 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 MacBook for sale by... Read more
B&H has 13-inch M2 MacBook Airs with 16GB...
B&H Photo has 13″ MacBook Airs with M2 CPUs, 16GB of memory, and 256GB of storage in stock and on sale for $1099, $100 off Apple’s MSRP for this configuration. Free 1-2 day delivery is available... Read more
14-inch M3 MacBook Pro with 16GB of RAM avail...
Apple has the 14″ M3 MacBook Pro with 16GB of RAM and 1TB of storage, Certified Refurbished, available for $300 off MSRP. Each MacBook Pro features a new outer case, shipping is free, and an Apple 1-... Read more
Apple M2 Mac minis on sale for up to $150 off...
Amazon has Apple’s M2-powered Mac minis in stock and on sale for $100-$150 off MSRP, each including free delivery: – Mac mini M2/256GB SSD: $499, save $100 – Mac mini M2/512GB SSD: $699, save $100 –... Read more
Amazon is offering a $200 discount on 14-inch...
Amazon has 14-inch M3 MacBook Pros in stock and on sale for $200 off MSRP. Shipping is free. Note that Amazon’s stock tends to come and go: – 14″ M3 MacBook Pro (8GB RAM/512GB SSD): $1399.99, $200... Read more

Jobs Board

*Apple* Systems Administrator - JAMF - Syste...
Title: Apple Systems Administrator - JAMF ALTA is supporting a direct hire opportunity. This position is 100% Onsite for initial 3-6 months and then remote 1-2 Read more
Relationship Banker - *Apple* Valley Financ...
Relationship Banker - Apple Valley Financial Center APPLE VALLEY, Minnesota **Job Description:** At Bank of America, we are guided by a common purpose to help Read more
IN6728 Optometrist- *Apple* Valley, CA- Tar...
Date: Apr 9, 2024 Brand: Target Optical Location: Apple Valley, CA, US, 92308 **Requisition ID:** 824398 At Target Optical, we help people see and look great - and Read more
Medical Assistant - Orthopedics *Apple* Hil...
Medical Assistant - Orthopedics Apple Hill York Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Now Read more
*Apple* Systems Administrator - JAMF - Activ...
…**Public Trust/Other Required:** None **Job Family:** Systems Administration **Skills:** Apple Platforms,Computer Servers,Jamf Pro **Experience:** 3 + years of Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.