Nicholas1010
Nicholas1010

Reputation: 1

Java: How to use Keyboard in program

I know that there is lots of sources of that but i can't find anything useful for me. so, - im creating little program/game. There is Dialogues Which asking stuff about character for example name, etc (i used Scanner for that) but now i need to make so that There will be chooseable options for example where you born: A. Something1 B. Something2 C. Something3. So when you press For example B on keyboard, you will choose "Something2". its little bit messed up question but please answer me, thanks.

Upvotes: 0

Views: 1797

Answers (2)

Cyrille Ka
Cyrille Ka

Reputation: 15523

If you are writing a game, I am guessing you are going to use Swing or AWT to display your stuff.

If it is the case, then you have to listen for key events. There are two ways:

Using KeyListener

You register listeners to your components. See Oracle's tutorial.

The problem here is that you may have several components and it's impractical to attach listener to all of them. On the other hand, if you just have a big Canvas, then there is no hassle to do it.

Using KeyboardFocusManager

You can listen to all key events in your application by adding a custom KeyEventDispatcher to the KeyboardFocusManager:

KeyboardFocusManager.getCurrentKeyboardFocusManager()
  .addKeyEventDispatcher(new KeyEventDispatcher() {
      @Override
      public boolean dispatchKeyEvent(KeyEvent e) {
        // your stuff
        return false;
      }
});

Upvotes: 1

Arpit
Arpit

Reputation: 12797

You need to use the key listener .

get the keycode from Keyboard and do the actions accordingly :

Here is the Tutorial : http://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html

Hint :

 public void keyTyped(KeyEvent e) {
        char keyPress=e.getKeyChar();
        if keyPress=='a' or 'A' 
            select option 1;

Upvotes: 1

Related Questions