Implementing Keyboard Events for Object Movement

KeyListener and Keyboard Events
Another type of listener listens for keyboard entry – the
KeyListener which generates KeyEvents
to implement KeyListener, you must implement three methods:
keyPressed, keyReleased and keyTyped
all three methods receive a KeyEvent
we typically will only implement one of these, probably keyPressed
(the other two must be defined but their bodies can be { })
the KeyEvent includes information about which key was pressed
getKeyChar – method to get the character pressed (e.g., ‘a’, ‘d’, ‘ ’)
– cannot be used for some keys like the arrow keys or enter key
getKeyCode – method to get a constant that defines the key, we
compare it against constants like KeyEvent.VK_LEFT or
KeyEvent.VK_ENTER (left arrow, enter key)
the JPanel which is to watch for keyboard entry must also be
focused on the keyboard using
panel.setFocusable(true);
Using Keyboard Input
What will keyboard entry be used for?
Select keys will control movement in a game
move around a maze
move the “sights” of a gun or a missile launcher
move a paddle (for instance in Pong or Breakout)
We need to designate certain keys for use
We will then place our logic to move the item in one of
the keyListener methods such as keyPressed
For instance, if a key is typed, in keyPressed we get the
key’s character and see if it was ‘a’ to move left or ‘d’
to move right and then adjust an x coordinate
We might then call repaint(); if we do not have a Timer,
otherwise, the Timer will call actionPerformed which
will call repaint();
Moving Objects
Let’s assume we have an object at coordinates x, y
We define a set of keys for data movement
for instance, the arrow keys or a, w, d, x for left, up, right, down
In keyPressed (or keyReleased or keyTyped), we test for
the character and make the proper movement in x or y
if(e.getKeyChar( ) = = ‘a’) x--;
else if(e.getKeyChar( ) = = ‘w’) y--;
else if(e.getKeyChar( ) = = ‘d’) x++;
else if(e.getKeyChar( ) = = ‘x’) y++;
Notice that we are not using an else statement here because
this method is called whenever ANY key is pressed, so the
statement else y++; would move the object down
whenever any key which is not ‘a’, ‘w’ or ‘d’ is pressed
We follow the above code with repaint( );
Borders
Imagine our drawing area is 500x500
We start at x=250,y=250
For each of a, w, d, x, we move the object accordingly
What happens if the user presses x 250 times?  x will be
500, can we draw something there?
Yes, but we will not see it
When we move the object in the keyPressed method,
we want to make sure it does not sound the object
beyond a border
We need to add code like this:
if(x>480) x=480; to force the object to “stop” moving
or if(x>480) x=20; to “wrap-around” to the other side of
the screen
Etch a Sketch Program
Let’s use the keyboard input to control the drawing
of short lines like the old etch a sketch game
This program requires a Graphics object to draw on and a
KeyListener
We use a single JPanel (we do not need a second JPanel
with GUI components as we do not need them for this
program), we will call this JPanel ESPanel
ESPanel requires the current x,y coordinate of the line
being drawn and the direction we want to extend the line
(up, down, left, right)
The direction will be controlled by the keyboard by using
the up, down, left or right arrows
The enter key will be used to “erase” the image, for this
we will set a boolean, setClear, to true upon pressing
enter and in paintComponent, if true, we will do
super.paintComponent(g) to erase the Graphics image
Methods
public void keyPressed(KeyEvent e) { 
       if(e.getKeyCode()==KeyEvent.VK_LEFT) direction = 0; 
       else if(e.getKeyCode()==KeyEvent.VK_UP) direction = 1; 
       else if(e.getKeyCode()==KeyEvent.VK_RIGHT) direction = 2; 
       else if(e.getKeyCode()==KeyEvent.VK_DOWN) direction = 3; 
       else if(e.getKeyCode()==KeyEvent.VK_ENTER setClear = true; 
       repaint( ); 
}
public void paintComponent(Graphics g) { 
         if(setClear) {
 
boolean super.paintComponent(g); 
 
setClear = false; 
          } 
          else {
 
 
g.setColor(Color.black); 
 
if(direction==0) {g.drawLine(x, y, x-2, y); x-=2; if (x < 10) x = 10;} 
 
else if(direction==1) { g.drawLine(x, y, x, y-2); y-=2; if (y < 10) y = 10; }
 
else if(direction== 2) { g.drawLine(x, y, x+2, y); x+=2; if (x > 290) x = 290;}
 
else if(direction==3) { g.drawLine(x, y, x, y+2); y+=2; if (y > 290) y = 290; }
        }
}
Typewriter Program
Another example is to allow the user to “type” on the Graphics
area while the mouse can be used to reposition the cursor
We use x,y for the coordinate of the cursor
A KeyListener is used to receive any key entries
In paintComponent, g.drawString outputs the latest input character at
the x, y coordinate and then the x coordinate is moved to the right
If the mouse is clicked, we retrieve its x, y coordinate and reposition
the cursor there
We do not need a Timer, the only change to the Graphics area is
when the user types something or uses the mouse, so both the
keyPressed (or keyTyped) and mousePressed (or mouseClicked)
methods call repaint
The class needs these variables
x, y for the coordinates of where the next character should appear
c the latest character obtained by a KeyEvent
We need to implement MouseListener and KeyListener on one
JPanel
Methods
public void mouseClicked(MouseEvent e) {
 
int tempX = e.getX(); 
 
int tempY = e.getY(); 
 
if(tempX > 10 && tempX < 290 && tempY > 10 && tempY < 290) { 
  
x = tempX; 
  
y = tempY;
 
}
}
public void keyTyped(KeyEvent e) {
 
key = e.getKeyChar(); 
 
repaint(); 
}
public void paintComponent(Graphics g) {
 
String temp = "" + key; 
 
g.setColor(Color,black);
 
drawString(temp, x, y); 
 
x+=7;
 
if(x>290) {
  
x=10;
  
y+=12;
 
}
}
 
We can also show the cursor by 
drawing a small triangle just below x, y
g.setColor(Color.red);
g.drawLine(x-1,y+1,x,y);
g.drawLine(x,y,x+1,y+1);
g.drawLine(x-1,y+1,x+1,y+1);
Maze
Today we have two projects, one is to implement a
maze
The maze will be drawn via paintComponent
We use a 2-D array of int values to indicate the path (0)
versus a wall (1) versus the exit (2)
For instance:
111111111111111111111111111111111
111100000000011111100000111110002
110001111111000000001010000000111
110100001111111111111000111011001
000111100000000000000011111000011
111111111111111111111111111111111
The user moves around the maze using keyboard input
Aside from making sure the user doesn’t move off the screen
(out of the array), we have to make sure the user doesn’t
move into a wall
More
Aside from the array, we need the current location
of the user (x, y)
When the user presses a key, we have to verify
that the move is available:
Moving in that direction does not move the user out of
the maze (beyond a border)
Moving in that direction does not take the user into a
wall
If the move passes both of those checks, then we
change the x or y coordinate appropriate and call
repaint, for instance, to move left, we use ‘a’
if(key==‘a’&&x>1&&maze[x-1][y]==0) x--;
this says:  “if the key is ‘a’, and the user is not on the
leftmost border, and the square being moved into is 0 (an
opening) then move to that square
Maze Program
This program will need a JPanel for drawing and
keyboard interaction
the JPanel class will implement KeyListener requiring
keyTyped (or keyPressed) be implemented
the JPanel class will contain a paintComponent
method to draw the maze (use maybe a 10x10 fillRect
for each array location where the color is set by the
array value, 0 might be white, 1 might be black and 2
might be red)
store x, y – the current location where x, y starts off as
the “entry” point of the maze
We also have to set the JPanel to be focusable –
we do this in main
MazePanel panel = new MazePanel( );
panel.setFocusable(true);
frame.add(panel);
Missile Launcher Game
Another project is to finish the missile launcher
We have a missile launcher at the bottom of the screen
which can move left/right
Press left arrow to start it moving left, right arrow for
right, space bar to launch a missile, and enter to stop it
moving
If we have 1 missile only, then we have to wait for the
missile to go off the screen before launching another – or
we can have an array of missiles (see the next slide)
Next, add an object to shoot at which can fly randomly on
the screen (use the Spaceship1 or Spaceship2 code)
Finally, determine if your missile hits the spaceship and if
so, add 1 to your score and reset the spaceship to randomly
be somewhere else
1 Missile vs Array of Missiles
1 missile requires its mx, my coordinate
it will move up at a constant speed, so at each Timer event,
we might do my=my-2;
its movement laterally might be 0 (its mx coordinate stays
the same once launched) or it might take on the same
change in x that the missile launcher has (that is, mdx=dx)
we have to keep track of the missile so that once missile
hits a border (left, right, top), we reset mx to -1 so that we
don’t draw it any more and can launch a new missile
For any number of missiles, make mx and my int
arrays and add a variable called numMissiles which
indicates which missile was the last to be launched
Use a for loop and an if statement to move and draw
the missiles:
for(int i=0;i<numMissiles;i++) if(mx[i]!=-1) {…}
Slide Note
Embed
Share

Learn how to implement KeyListener and handle Keyboard Events in Java to control object movement in games. Understand how to use keyPressed method, KeyEvent, getKeyChar, and getKeyCode for smooth navigation. Explore examples for controlling objects using arrow keys and avoiding border issues.

  • Java Programming
  • Object Movement
  • KeyListener
  • Keyboard Events
  • Game Development

Uploaded on Feb 19, 2025 | 0 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.

E N D

Presentation Transcript


  1. KeyListener and Keyboard Events Another type of listener listens for keyboard entry the KeyListener which generates KeyEvents to implement KeyListener, you must implement three methods: keyPressed, keyReleased and keyTyped all three methods receive a KeyEvent we typically will only implement one of these, probably keyPressed (the other two must be defined but their bodies can be { }) the KeyEvent includes information about which key was pressed getKeyChar method to get the character pressed (e.g., a , d , ) cannot be used for some keys like the arrow keys or enter key getKeyCode method to get a constant that defines the key, we compare it against constants like KeyEvent.VK_LEFT or KeyEvent.VK_ENTER (left arrow, enter key) the JPanel which is to watch for keyboard entry must also be focused on the keyboard using panel.setFocusable(true);

  2. Using Keyboard Input What will keyboard entry be used for? Select keys will control movement in a game move around a maze move the sights of a gun or a missile launcher move a paddle (for instance in Pong or Breakout) We need to designate certain keys for use We will then place our logic to move the item in one of the keyListener methods such as keyPressed For instance, if a key is typed, in keyPressed we get the key s character and see if it was a to move left or d to move right and then adjust an x coordinate We might then call repaint(); if we do not have a Timer, otherwise, the Timer will call actionPerformed which will call repaint();

  3. Moving Objects Let s assume we have an object at coordinates x, y We define a set of keys for data movement for instance, the arrow keys or a, w, d, x for left, up, right, down In keyPressed (or keyReleased or keyTyped), we test for the character and make the proper movement in x or y if(e.getKeyChar( ) = = a ) x--; else if(e.getKeyChar( ) = = w ) y--; else if(e.getKeyChar( ) = = d ) x++; else if(e.getKeyChar( ) = = x ) y++; Notice that we are not using an else statement here because this method is called whenever ANY key is pressed, so the statement else y++; would move the object down whenever any key which is not a , w or d is pressed We follow the above code with repaint( );

  4. Borders Imagine our drawing area is 500x500 We start at x=250,y=250 For each of a, w, d, x, we move the object accordingly What happens if the user presses x 250 times? x will be 500, can we draw something there? Yes, but we will not see it When we move the object in the keyPressed method, we want to make sure it does not sound the object beyond a border We need to add code like this: if(x>480) x=480; to force the object to stop moving or if(x>480) x=20; to wrap-around to the other side of the screen

  5. Etch a Sketch Program Let s use the keyboard input to control the drawing of short lines like the old etch a sketch game This program requires a Graphics object to draw on and a KeyListener We use a single JPanel (we do not need a second JPanel with GUI components as we do not need them for this program), we will call this JPanel ESPanel ESPanel requires the current x,y coordinate of the line being drawn and the direction we want to extend the line (up, down, left, right) The direction will be controlled by the keyboard by using the up, down, left or right arrows The enter key will be used to erase the image, for this we will set a boolean, setClear, to true upon pressing enter and in paintComponent, if true, we will do super.paintComponent(g) to erase the Graphics image

  6. public void keyPressed(KeyEvent e) { if(e.getKeyCode()==KeyEvent.VK_LEFT) direction = 0; else if(e.getKeyCode()==KeyEvent.VK_UP) direction = 1; else if(e.getKeyCode()==KeyEvent.VK_RIGHT) direction = 2; else if(e.getKeyCode()==KeyEvent.VK_DOWN) direction = 3; else if(e.getKeyCode()==KeyEvent.VK_ENTER setClear = true; repaint( ); } Methods public void paintComponent(Graphics g) { if(setClear) { boolean super.paintComponent(g); setClear = false; } else { g.setColor(Color.black); if(direction==0) {g.drawLine(x, y, x-2, y); x-=2; if (x < 10) x = 10;} else if(direction==1) { g.drawLine(x, y, x, y-2); y-=2; if (y < 10) y = 10; } else if(direction== 2) { g.drawLine(x, y, x+2, y); x+=2; if (x > 290) x = 290;} else if(direction==3) { g.drawLine(x, y, x, y+2); y+=2; if (y > 290) y = 290; } } }

  7. Typewriter Program Another example is to allow the user to type on the Graphics area while the mouse can be used to reposition the cursor We use x,y for the coordinate of the cursor A KeyListener is used to receive any key entries In paintComponent, g.drawString outputs the latest input character at the x, y coordinate and then the x coordinate is moved to the right If the mouse is clicked, we retrieve its x, y coordinate and reposition the cursor there We do not need a Timer, the only change to the Graphics area is when the user types something or uses the mouse, so both the keyPressed (or keyTyped) and mousePressed (or mouseClicked) methods call repaint The class needs these variables x, y for the coordinates of where the next character should appear c the latest character obtained by a KeyEvent We need to implement MouseListener and KeyListener on one JPanel

  8. public void mouseClicked(MouseEvent e) { int tempX = e.getX(); int tempY = e.getY(); if(tempX > 10 && tempX < 290 && tempY > 10 && tempY < 290) { x = tempX; y = tempY; } } public void keyTyped(KeyEvent e) { key = e.getKeyChar(); repaint(); } public void paintComponent(Graphics g) { String temp = "" + key; g.setColor(Color,black); drawString(temp, x, y); x+=7; if(x>290) { x=10; y+=12; } } Methods We can also show the cursor by drawing a small triangle just below x, y g.setColor(Color.red); g.drawLine(x-1,y+1,x,y); g.drawLine(x,y,x+1,y+1); g.drawLine(x-1,y+1,x+1,y+1);

  9. Maze Today we have two projects, one is to implement a maze The maze will be drawn via paintComponent We use a 2-D array of int values to indicate the path (0) versus a wall (1) versus the exit (2) For instance: 111111111111111111111111111111111 111100000000011111100000111110002 110001111111000000001010000000111 110100001111111111111000111011001 000111100000000000000011111000011 111111111111111111111111111111111 The user moves around the maze using keyboard input Aside from making sure the user doesn t move off the screen (out of the array), we have to make sure the user doesn t move into a wall

  10. More Aside from the array, we need the current location of the user (x, y) When the user presses a key, we have to verify that the move is available: Moving in that direction does not move the user out of the maze (beyond a border) Moving in that direction does not take the user into a wall If the move passes both of those checks, then we change the x or y coordinate appropriate and call repaint, for instance, to move left, we use a if(key== a &&x>1&&maze[x-1][y]==0) x--; this says: if the key is a , and the user is not on the leftmost border, and the square being moved into is 0 (an opening) then move to that square

  11. Maze Program This program will need a JPanel for drawing and keyboard interaction the JPanel class will implement KeyListener requiring keyTyped (or keyPressed) be implemented the JPanel class will contain a paintComponent method to draw the maze (use maybe a 10x10 fillRect for each array location where the color is set by the array value, 0 might be white, 1 might be black and 2 might be red) store x, y the current location where x, y starts off as the entry point of the maze We also have to set the JPanel to be focusable we do this in main MazePanel panel = new MazePanel( ); panel.setFocusable(true); frame.add(panel);

  12. Missile Launcher Game Another project is to finish the missile launcher We have a missile launcher at the bottom of the screen which can move left/right Press left arrow to start it moving left, right arrow for right, space bar to launch a missile, and enter to stop it moving If we have 1 missile only, then we have to wait for the missile to go off the screen before launching another or we can have an array of missiles (see the next slide) Next, add an object to shoot at which can fly randomly on the screen (use the Spaceship1 or Spaceship2 code) Finally, determine if your missile hits the spaceship and if so, add 1 to your score and reset the spaceship to randomly be somewhere else

  13. 1 Missile vs Array of Missiles 1 missile requires its mx, my coordinate it will move up at a constant speed, so at each Timer event, we might do my=my-2; its movement laterally might be 0 (its mx coordinate stays the same once launched) or it might take on the same change in x that the missile launcher has (that is, mdx=dx) we have to keep track of the missile so that once missile hits a border (left, right, top), we reset mx to -1 so that we don t draw it any more and can launch a new missile For any number of missiles, make mx and my int arrays and add a variable called numMissiles which indicates which missile was the last to be launched Use a for loop and an if statement to move and draw the missiles: for(int i=0;i<numMissiles;i++) if(mx[i]!=-1) { }

More Related Content

giItT1WQy@!-/#