Question

I am studying about GUI in java. Now, i am coding a tiny program about button, and i have a question. In common, i use mouse to click a button and i set a Message Dialog appear but now, I want to set a method. In this method, i use KeyEvent, i want to press a key and the program will automatically choice the button without mouse. I have used TextArea and TextField and now i want to use this method without TextArea and TextField. Example: when i click the button, the message dialog appear, now instead of click the button, when i press A, the message dialog will appear. Please help me !

Was it helpful?

Solution

For larger event-handling I suggest @Chris' suggestion but for something as small as yours - i.e., calling a simple method upon keyPress, I'd personally go with an anonymous listener

.addKeyListener(new KeyListener() {  
    public void keyPressed(KeyEvent e) {  
        //method call goes here 
    }  
});

OTHER TIPS

You can add a KeyListener to your JFrame. Here is an excellent tutorial.

Example

Let's create a class that implements our KeyListener, and let's assume you've got a class that extends JFrame, called Program.

public class KeyMapper implements KeyListener
{
    // Lots of methods will need to be written. I won't do them all.

    private Program world;

    public KeyMapper(Program world)
    {
         this.world = world;  
    }

    /**
     * This is the event that fires when a key is hit.
     * @param e the event object passed when a key is hit.
     * @Override
     */
    public void keyTyped(KeyEvent e) {
         if(e.getKeyChar() == 't') {
             world.callMethod(); 
         }
    }
}

KeyMapper will now call a method in your program, whenever t is hit. To add this to your Program, you can use the following line:

this.addKeyListener(new KeyMapper(this));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top