import java.awt.*; import java.util.*; public class KeyCounter extends Frame { private static int NUMBER_OF_UNICODE_CODES = 65536; private static int ONE_SECOND = 1000; // 1 s = 1000 millis private static int FIRST_ASCII = 0; private static int LAST_ASCII = 127; private static int ASCII_SPACE = 32; private static int ASCII_DEL = 127; // array to accumulate stats in protected int keys[] = new int[NUMBER_OF_UNICODE_CODES]; protected int total = 0; // total keys pressed protected Date then = new Date(); // take a timestamp at init //------------------------------------------------------------------- // main() entry point //------------------------------------------------------------------- public static void main (String[] args) { new KeyCounter(); } //------------------------------------------------------------------- // KeyCounter Constructor //------------------------------------------------------------------- public KeyCounter() { super("KeyCounter demo: please type characters"); TextArea ta = new TextArea(); ta.setText("Start typing.. 20 seconds to go.."); add(ta); new KeyCounterAdapter(this, ta); setSize(new Dimension(400,300)); setVisible(true); } //------------------------------------------------------------------- // The original key event processing method. // This method is now "adapted" to the 1.1 event mechanism via an // adapter object which acts on behalf of the KeyCounter object. //------------------------------------------------------------------- public void hereAnotherKey( char key ) { keys[ (int)key ]++; total++; // record key presses for 20 seconds... if ( new Date().getTime() - then.getTime() > 20*ONE_SECOND ) { // then.. dumpKeyStatistics(); System.exit(0); } } //------------------------------------------------------------------- // Dump frequency of all ASCII chars which were typed //------------------------------------------------------------------- private void dumpKeyStatistics() { for (int keyCode=FIRST_ASCII; keyCode <= LAST_ASCII; keyCode++) { if ( keys[keyCode] != 0 ) { char glyph; if ( keyCode < ASCII_SPACE || keyCode == ASCII_DEL ) { glyph = '.'; } else { glyph = (char) keyCode; } System.out.println("Key '"+ glyph +"' (code "+ keyCode + ") pressed "+ keys[keyCode] +" times." ); } // endif } // endfor } } // End of Class KeyCounter