Please enable JavaScript to use CodeHS

Java Swing Keyboard Events

In this tutorial, students will look at keyboard events in Java Swing. The tutorial assumes some understanding of Java and basic Java Swing. Students will create a rectangle object and use keyboard inputs to alter that object.

By David Burnham

Introduction

In other Java Swing tutorials, you saw how to create an app using buttons and button events. This tutorial takes a different direction looking at drawing objects and keyboard events on a graphical canvas. This tutorial is similar to the Mouse Events tutorial, except you are using the keyboard instead of a mouse.

Like the other Swing tutorials, you will still be starting with a JFrame, but this tutorial used a few different methods to help create the paint objects and keyboard events.

Creating A Rectangle

This tutorial is not going to go in-depth on Java Swing objects, but it does look at how to create a Java Swing Canvas and draw an object, in this case, a rectangle.

The setup of your project is similar to before, except now your class is going to extend the abstract JPanel class. By extending this, you are required to add the paintComponent(Graphics g) method. This is the method that will draw out objects.

The Graphics object, g, will be used to add different graphic objects to our panel. Inside the paintComponent method, your first statement should be to call the parent’s paintComponent method with the super command. This tutorial is not going to get into the details of abstract classes or inheritance, but know that this line is important.

From there, you can call methods to create objects. You are going to use two commands in this tutorial, setColor and fillRect.

setColor allows you to set the active color. Any objects that are drawn will use this color until it is changed. It can take several options, but in the example below, you should notice it uses a color name and a red, green, blue combo.

The fillRect command takes 4 integers. The first two are the coordinates for the upper left corner of the rectangle and the second two are the width and height of the rectangle.

Play around with some of the options below and create your own squares and rectangles.

Keyboard Events

As the name implies, a keyboard event is called each time something happens on the keyboard. There are actually 3 different keyboard events, key pressed, key released, and key typed. You will be using the key pressed event in this tutorial.

In the example below, the program creates a blue square that grows in size when the up arrow is pressed and shrinks when the down arrow is pressed.

Changes to the Example Below

There are a few changes that need to be made to accommodate the keyboard event. First, there is now an extra instance variables, size to represent the currrent size of the box. The value for size will be updated in the key pressed event and then when the repaint is called, the box gets redrawn with the new size. Inside of the paint method, you will also see a pos variable that is used to set the position. This will ensure the box stays in the same place as it grows and shrinks.

Second, the keyboard listener was added to the createAndShowGUI method. This command is called each time something happens with the keyboard. Inside that command, you see the embedded keyPressed method with the parameter e. This parameter holds information about the event, including which key was pressed. Notice how the program uses if statements to determine which action to take based on which key is pressed. The keys are represented with a code, for example VK_UP represents the up key. You can see a complete list of the codes on the Java Website

The final step of the process is to call the repaint() command. When this command is called, it triggers the paintComponent method to run again and refresh the screen.

Important Note: When you run the program, to get the keyboard to work, first click in the frame to make it the active window, otherwise your key strokes will go into the console and not register with the frame.

Adding More Keys

In this final example, you are going to add a few more keys to make your program a little more interesting. You will add the c key to change the color of the box and the r key to reset the box back to the start.

To help with this, you will introduce a color array to hold the red, green, and blue values for the color. You will set these to 100, 100, 100 to start, which is a medium gray value.

Inside the keyPressed method, you will see two new if statements, one for the c key and one for the r key. The c key will loop through and update the color array with random numbers between 0 and 255 and the r key will reset the color and size back to the original values.

Adding your personal touch

What else can you do? Add your own keys to the project and see what else you can make. For example, can you add W, A, S, and D to move the box around? What other instance variables would you need?

Have fun and explore!