How can I Implement KeyListeners/ActionListeners into the JFrame?
Posted
by
A.K.
on Game Development
See other posts from Game Development
or by A.K.
Published on 2012-06-11T19:22:46Z
Indexed on
2012/06/11
22:48 UTC
Read the original article
Hit count: 321
java
|game-mechanics
I'll get to the point: I have a player in my game that you control with the keyboard yet the key methods in the player class and ActionListener w/ KeyAdapter in the Board class don't seem to fire.
So far I've tried adding these key methods into the JFrame, doesn't seem to let me move him even though other objects that I have (enemies) can move fine.
Here's part of the JFrame class with the event listeners:
frm.addKeyListener(KeyBoardListener);
public void mouseClicked(MouseEvent e)
{
nSound.play();
StartB.setContentAreaFilled(false);
cards.remove(StartB);
frm.remove(TitleL);
frm.remove(cards);
frm.setLayout(new GridLayout(1, 1));
frm.add(nBoard); //Add Game "Tiles" Or Content. x = 1200
nBoard.setPreferredSize(new Dimension(1200, 420));
cards.revalidate();
frm.validate();
}
public KeyListener KeyBoardListener = new KeyListener()
{
@Override
public void keyPressed(KeyEvent args0)
{
int key = args0.getKeyCode();
if(key == KeyEvent.VK_LEFT)
{
nBoard.S.vx = -4;
}
if(key == KeyEvent.VK_RIGHT)
{
nBoard.S.vx = 4;
}
if(key == KeyEvent.VK_UP)
{
nBoard.S.vy = -4;
}
if(key == KeyEvent.VK_DOWN)
{
nBoard.S.vy = 4;
}
if(key == KeyEvent.VK_SPACE)
{
nBoard.S.fire();
}
}
@Override
public void keyReleased(KeyEvent args0)
{
int key = args0.getKeyCode();
if(key == KeyEvent.VK_LEFT)
{
nBoard.S.vx = 0;
}
if(key == KeyEvent.VK_RIGHT)
{
nBoard.S.vx = 0;
}
if(key == KeyEvent.VK_UP)
{
nBoard.S.vy = 0;
}
if(key == KeyEvent.VK_DOWN)
{
nBoard.S.vy = 0;
}
}
@Override
public void keyTyped(KeyEvent args0) {
// TODO Auto-generated method stub
}
};
© Game Development or respective owner