Source code: jpl2/common/gui/ButtonKeyAdapter.java
1 /***********************************************************************
2 * JavaPsionLink 2.0, a java implementation of the psion link protocol
3 * Copyright (C) 2002, 2003 John S Montgomery (john.montgomery@lineone.net)
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU Lesser General Public License as published by
7 * the Free Software Foundation; either version 2.1 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU Lesser General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18 ************************************************************************/
19 package jpl2.common.gui;
20
21 import java.awt.*;
22 import java.awt.event.*;
23
24 public class ButtonKeyAdapter extends KeyAdapter {
25 private Component button = null;
26 private int keyCode = -1;
27 private Class JButtonClass = null;
28
29 public ButtonKeyAdapter( Component button, int keyCode ) {
30 this.button = button;
31 this.keyCode = keyCode;
32 }
33
34 private void clickButton() {
35 // fire off an event on the button
36 // if we are using mrj we can programmatically press the button, which looks nicer
37 if ( System.getProperty( "mrj.version" ) != null && button instanceof Button )
38 button.dispatchEvent( new KeyEvent( button, KeyEvent.KEY_PRESSED, System.currentTimeMillis(), 0, KeyEvent.VK_ENTER, (char)KeyEvent.VK_ENTER ) );
39 else if ( button instanceof Button )
40 button.dispatchEvent( new ActionEvent( button, ActionEvent.ACTION_PERFORMED, ((Button)button).getActionCommand() ) );
41 else {// must be a swing button, in which case we can also press the button programmatically
42 try {
43 Class abstractButtonClass = Class.forName( "javax.swing.AbstractButton" );
44 if ( abstractButtonClass.isInstance( button ) ) {
45 // yep it is - now call it's doClick(int) method
46 int millisPressed = 250;
47 button.getClass().getMethod( "doClick", new Class[]{ Integer.TYPE } ).invoke( button, new Object[] { new Integer( millisPressed ) } );
48 }
49 }
50 catch( Throwable t ) {
51 }
52 }
53 }
54
55 public void keyReleased( KeyEvent ke ) {
56 if ( ke.getKeyCode() == keyCode && ke.getModifiers() == 0 ) {
57 clickButton();
58 ke.consume();
59 }
60 }
61
62 }