This is the code for a key listener that controls the movement of an ImageIcon. I want to prevent the clicking of other keys from stopping the movement of the image, but I still want other keys to do things, just not stop the image's movement. I don't know if it's a focus issue, but I've tried using grabFocus() when the space bar is clicked to to no avail. I've also tried Key Bindings which turn out to have glitchy animations and also have the same issue.
For example, let's say I'm holding down the right arrow key, so my sprite is moving right, and then I click the space bar while I'm holding down the right key. With my code, that click stops my sprite's movement. I want the space bar to have a purpose, but I want it to not stop the sprite.
public void actionPerformed(ActionEvent e){ // image and graphics stuff is elsewhere in the code
x += velx; // x and y are declared above
y += vely;
repaint();
}
public void up()
{
vely = -1;
velx = 0;
}
public void down()
{
vely = 1;
velx = 0;
}
public void left()
{
vely = 0;
velx = -1;
}
public void right()
{
vely = 0;
velx = 1;
}
public void keyPressed(KeyEvent e)
{
int key = e.getKeyCode();
if(key==KeyEvent.VK_UP)
{
up();
i = 0;
}
if(key==KeyEvent.VK_DOWN)
{
down();
i = 1;
}
if(key==KeyEvent.VK_LEFT)
{
left();
i = 2;
}
if(key==KeyEvent.VK_RIGHT)
{
right();
i = 3;
}
if(key == KeyEvent.VK_SPACE)
{
j = 0;
spaceClicked = true;
}
}
public void keyReleased(KeyEvent e)
{
int key = e.getKeyCode();
if(key == KeyEvent.VK_UP || key == KeyEvent.VK_DOWN)
vely = 0;
else
velx = 0;
}
public void keyTyped(KeyEvent e)
{
}
Any help would be appreciated, thanks.