The Java Game Framework.

Examples, tutorials, documentation and download of the Genuts Framework.
Games made with the Genuts Frameworks.
General articles around games.
Links covering all needs around game dev.
Who are we?
Terms of Service

API >> Tutorials >> Interfacing Genuts Framework and Java API >>Controlling a sprite with the keyboard

Controlling a sprite with the keyboard

Java AWT API offers events to catch keyboard actions, mouse actions, and so on…
We will see now how to interface them with the Genuts Framework.

  Type a key to switch between hours mode and date mode.

Interfacing events principles

AWT events are processed in their own thread; therefore, we have to be cautious.
To avoid conflicts between Genuts thread and AWT events, we have to change only states of our objects, and not to move or resize them somewhere else than in playfield's ticks.

Now the question is: where is the right place of the event listener?
That depends on what you need.
There are 2 possible possibilities:

  • If you have several sprites to control with the same type of events, it is better to have only one listener which dispatches actions between sprites.
  • If only one sprite is concerned by a type of events, it is better to make a sprite wrapper and to wrap the desired sprite.

Keyboard events

In this section, we will use keyboard events to switch the TimeWrapper between hours display and date display. We will explain the simplest way to process with events.

The KeyListener is implemented directly in the Applet object: KeyTimeApplet.
We keep a reference to the TimeWrapper object to modify its state when it is needed. Here is the code which deals with events from the keyboard:


...
  public void keyTyped(KeyEvent e) {
    if (timeSprite.getDisplay() != TimeWrapper.DISPLAY_DATE) {
      timeSprite.setDisplay(TimeWrapper.DISPLAY_DATE);
    } else {
      timeSprite.setDisplay(TimeWrapper.DISPLAY_24HOURS);
    }
  }
...

And we only have to associate the KeyListener to the playfield:


...
    // Adds this applet as KeyListener to the playfield
    playfield.addKeyListener(this);
...

In start() method of your applet we suggest you to request the focus for the playfield. In that way, the user doesn't need to click in the applet before it types a key:


...
  public void start() {
    // Activate the playfield
    playfield.setPause(false);

    // Request the focus for the playfield
    playfield.requestFocus();
  }
...

Now what about mouse events?

<< Previous Page Next Page >>

API >> Tutorials >> Interfacing Genuts Framework and Java API >>Controlling a sprite with the keyboard