ADC Home > Reference Library > Technical Q&As > Legacy Documents > Java >

Legacy Documentclose button

Important: This document is part of the Legacy section of the ADC Reference Library. This information should not be used for new development.

Current information on this Reference Library topic can be found here:

Simulated Click on AWT Button


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);
        }
    }
}
  

[Feb 03 1999]


Did this document help you?
Yes: Tell us what works for you.
It’s good, but: Report typos, inaccuracies, and so forth.
It wasn’t helpful: Tell us what would have helped.