LightMikeE
LightMikeE

Reputation: 729

Create an actionlistener(?) in Java

So I searched Stackoverflow, but couldn't find any actual answer that I got. If there's already an answer to this question, please tell me.

I have a class with a showDescription method. This prints a string variable.

I require this method to be called whenever the "d" key is pressed, in the main method. So, what would the code be to implement the key press/down event?

Upvotes: 0

Views: 67

Answers (1)

Carlos Castellanos
Carlos Castellanos

Reputation: 2378

Do this if you have a swing application:

f.addKeyListener(new KeyListener() {

            @Override
            public void keyTyped(KeyEvent e) {
            }

            @Override
            public void keyPressed(KeyEvent e) {
                if ((e.getKeyCode() == KeyEvent.VK_D) && ((e.getModifiers() & KeyEvent.CTRL_MASK) != 0)) {
                    System.out.println("woot!");
                }
            }

            @Override
            public void keyReleased(KeyEvent e) {
            }
        });

you can read more here and here

If you have a console application then use:

Read Input until control+d

Upvotes: 1

Related Questions