Navigation Menu

Home
Games
Developer's Corner
Members
About

Forums
Contact
Project Viltris
Back to Developer's Corner

Java Game Development Tutorials
00 - Introduction & Tips
01 - Applets
02 - Events

Java Game Development Tutorial #2

Events


Key Events

A big part of computer programs is accepting input from the user. In our examples so far, we have been missing that--input. Unfortunately, keyboard input isn't quite as simple for applets as it was for command-line applications (and even that was pretty complicated). This section will go over the basics of keyboard input for graphical programs.

Now, we'll need to use an interface called KeyListener. This interface has the following method prototypes:
Basically, you implement the KeyListener, and whenever a Key Event happens, the corresponding method will be called. keyPressed() and keyReleased() should be intuitive. A key is considered "typed" when a key is pressed, released, and generates a printable character, for example 'A'.

Of course, it's not enough to just know that an event happened. In the case of the keyboard, we want to know what the user pressed. The key (no pun intended) is in the KeyEvent object that is passed to the listener methods. A call to the method e.getKeyCode() will return an integer. Comparing this integer to constants such as KeyEvent.VK_A, KeyEvent.VK_0, KeyEvent.VK_SHIFT, KeyEvent.VK_CONTROL, KeyEvent.VK_LEFT, and other similar constants will allow us to figure out which key was pressed. (For the whole list of KeyEvent constants, look at the API on java.sun.com.)

Another useful method is e.getKeyChar(), which returns the char generated by a key typed event. (It's not guaranteed to be meaningful for key pressed or key released events.)

A few more details: First, a key event listener needs to be registered to the object it's listening to. To do this, we call the method addKeyListener(KeyListener listener) on the object that will produce these events and pass to it the listener. For example, if bob was generating key events and sarah was a listener listening for these events, then we would write bob.addKeyListener(sarah).

Second, in order for an object to produce events, it needs to have "focus". In our example above, we would have to write bob.requestFocus() so that bob could accept input from the keyboard and generate key events.

Last, when an event happens, usually, we want this change to be reflected on the screen. However, Java is not smart enough to repaint the applet every time an event happens. (In fact, sometimes we don't want to repaint the screen every time.) In this case, we should call the method repaint(), a member function of applet, to repaint the screen for us.

Enough talking, time for an example:

/* KeyDemo.java */ import java.applet.*; import java.awt.*; import java.awt.event.*; public class KeyDemo extends Applet implements KeyListener { int cx = 150, cy = 150; char theKey = '?'; Font theFont = new Font("Serif", Font.BOLD, 36); public void init() { setFont(theFont); addKeyListener(this); requestFocus(); } public void paint(Graphics g) { g.drawString("" + theKey, cx, cy); } public void keyPressed(KeyEvent e) { int code = e.getKeyCode(); if (code == KeyEvent.VK_UP) { cy -= 10; repaint(); } else if (code == KeyEvent.VK_DOWN) { cy += 10; repaint(); } else if (code == KeyEvent.VK_LEFT) { cx -= 10; repaint(); } else if (code == KeyEvent.VK_RIGHT) { cx += 10; repaint(); } } public void keyReleased(KeyEvent e) { } public void keyTyped(KeyEvent e) { theKey = e.getKeyChar(); repaint(); } }

Note that the line addKeyListener(this) basically has our applet registering itself to itself as both the listener and event generator.

The way the applet works is that you press the arrow keys to move the character, and you hit any printable key on the keyboard to change the character.

Here's some output with a 300x300 applet. In this case, I moved the character up to the upper-left and pressed '1', then moved it to the lower-right and pressed '2'.

Tutorial #2 - Key Demo Tutorial #2 - Key Demo

Mouse Events

Similarly, there's a MouseListener interface, which allows us to listen to mouse events. Its methods are as follows:
And the class MouseEvent has the following useful functions:

int getX() - get the X-coordinate of the mouse event
int getY() - get the Y-coordinate of the mouse event
int getButton() - get the button used for the mouse event; can return MouseEvent.NOBUTTON, MouseEvent.BUTTON1 (left-click), MouseEvent.BUTTON2 (middle button), and MouseEvent.BUTTON3 (right-click)

Note that these mouse button constants are for a 3-button mouse. It is not known whether these constants are correct for a 2-button or (god forbid) 1-button mouse, due to lack of hardware to test with.

Now, for an example:

/* MouseDemo.java */ import java.applet.*; import java.awt.*; import java.awt.event.*; public class MouseDemo extends Applet implements MouseListener { int x, y; boolean pressed = false; boolean inApplet = true; boolean rToggle = false; public void init() { addMouseListener(this); } public void paint(Graphics g) { if (rToggle) { g.setColor(Color.RED); } else { g.setColor(Color.BLUE); } if (inApplet) { if (pressed) { g.drawString("Waiting for mouse release", 20, 50); } else { g.drawString("Mouse was released at (" + x + ", " + y + ")", 20, 50); } } else { g.drawString("Come back!", 20, 50); } } public void mousePressed(MouseEvent e) { int button = e.getButton(); if (button == MouseEvent.BUTTON1) { pressed = true; repaint(); } } public void mouseReleased(MouseEvent e) { int button = e.getButton(); if (button == MouseEvent.BUTTON1) { pressed = false; x = e.getX(); y = e.getY(); repaint(); } } public void mouseClicked(MouseEvent e) { int button = e.getButton(); if (button == MouseEvent.BUTTON3) { rToggle = !rToggle; repaint(); } } public void mouseEntered(MouseEvent e) { inApplet = true; repaint(); } public void mouseExited(MouseEvent e) { inApplet = false; repaint(); } }

The way this applet works is when you click and release the mouse (or hold and release the mouse), it'll give you the coordinates of where the mouse was last released. If the mouse leaves the applet, it'll print a message. You can right-click to toggle the color between red and blue.

Here's some sample output with a 300x100 applet:

Tutorial #2 - Mouse Demo Tutorial #2 - Mouse Demo

Mouse Motion

But mouse clicks and releases aren't the only thing we can detect. We can also generate events whenever the mouse moves. However, mouse motion events are generated so quickly that the Java creators decided to create an extra interface for that, called MouseMotionListener, with the following methods:

void mouseMoved(MouseEvent e) - mouse motion with the mouse buttons released
void mouseDragged(MouseEvent e) - mouse motion with the mouse buttons pressed

And here's an example demonstrating the use of the Mouse Motion events:

/* MouseMotionDemo.java */ import java.applet.*; import java.awt.*; import java.awt.event.*; public class MouseMotionDemo extends Applet implements MouseListener, MouseMotionListener { int rx = 50; int ry = 50; int oldx, oldy; boolean dragging = false; public void init() { addMouseListener(this); addMouseMotionListener(this); } public void paint(Graphics g) { g.fillRect(rx, ry, 100, 50); } public void mousePressed(MouseEvent e) { int x = e.getX(); int y = e.getY(); if (rx <= x && x <= rx+100 && ry <= y && y <= ry+50) { oldx = x; oldy = y; dragging = true; } } public void mouseReleased(MouseEvent e) { } public void mouseClicked(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { dragging = false; } public void mouseMoved(MouseEvent e) { } public void mouseDragged(MouseEvent e) { if (dragging) { int x = e.getX(); int y = e.getY(); rx += x - oldx; ry += y - oldy; oldx = x; oldy = y; repaint(); } } }

Basically, this applet allows you to drag and drop a rectangle.

Here is some sample output in a 300x300 applet:

Tutorial #2 - Mouse Motion Demo Tutorial #2 - Mouse Motion Demo

You might have noticed that when you drag the rectangle, it flickers. Badly. We'll teach you how to alleviate that with animation techniques, but that's for next time.

Conclusion

Now that we know how to accept input in our applets, we can start making simple games. Anything where all you need to do is respond to mouse clicks and motions and key presses is already doable.

Next time, as promised, we're going to tell you how to draw images. Not only that, but we're going to teach you a few animation techniques so that you can start making action games. Onward, to Tutorial #3: Images & Animation!

Homework Assignment!

Now that you know how to make simple games, we want you to do precisely that. Just a simple applet will do. Popular options include: (The options marked with a * may be somewhat more challenging.)

Input may be either with the mouse or the keyboard. Bonus points if you allow the user to use either.