★ wanayoo — archive 1999 http://developer.apple.com/qa/java/java01.htmlNouvelle recherche | Portail wanayoo
Apple - Developer

ADC Home Page Membership Home Page Technical Home Page Business Home Page Log In ADC Site Map Search ADC Site

Technical Q&A

Java 01 - Simulated Click on AWT Button (Updated 3-February-1999)


Q: How do I programmatically make my java.awt.Button behave as if it were clicked on by the user?

A: This is typically desired when implementing default buttons and giving feedback that the default button action was performed when the Enter or Return key was pressed. There are other instances where this makes good sense from a user interface standpoint. The Macintosh Runtime for Java (MRJ) has provisions for this behavior built in. To get this behavior you need to pass a key-pressed event to the target button. Here is an example of how this could be achieved:

import
java.awt.Button;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;

public class SimulateClick
{
	 /**
	 * A function to simulate a click on the target button.
	 * This will make the button draw as if it had been pressed and
	 * released, and the button will fire an Action event as if
	 * the button were pressed.
	 * For use with the Apple MRJ 2.1 EA3 and later.
	 */
	static protected void simulateClick(Button target)
	{
		if (target != null)
		{
			KeyEvent keyEvent = 
	new KeyEvent(target, KeyEvent.KEY_PRESSED, 
       System.currentTimeMillis(), 0, KeyEvent.VK_ENTER, 
	   (char)KeyEvent.VK_ENTER);
			target.dispatchEvent(keyEvent);
		}
	}
}
  


-- Levi Brown
Worldwide Developer Technical Support

Technical Q&A | Contents
Next Question

To contact us, please use the Contact Us page.
Gray line
 
Site Map | Search Tips | Options | Keywords

Contact Us | Privacy Notice
Copyright © 2000 Apple Computer, Inc. All rights reserved.
1-800-MY-APPLE