This week's book giveaway is in the OCAJP forum.
We're giving away four copies of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) and have Khalid A Mughal & Rolf W Rasmussen on-line!
See this thread for details.
Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Multiple Key Press

 
rob starteren
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Trying to figure out the animation framework in Java and i managed to get a box to move around a JFrame.

I can move up down left and right using the arrow keys. How can i tell the box to move diagonally up without using a new key.

So how do i know if the user pressed the up and right key at the same time to make the box move diagonally up to the right?

if(evt.getKeyCode()==39)
{
posX ++;
direction="right";
}
else if((evt.getKeyCode()==38))
{
posY --;
direction="down";
}


else if((evt.getKeyCode()==40))
{
posY ++;
direction="up";
}
else if((evt.getKeyCode()==37))
{
posX --;
direction="left";
}

System.out.println(evt.getKeyCode());

Because if i hold up and right at the same time it just registers that as 2 single events. Any ideas?
 
Rob Spoor
Sheriff
Pie
Posts: 20608
63
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You already found out that it is two events. So in between those two events, you should keep track of all relevant key presses.

In this case:
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic