How can I Implement KeyListeners/ActionListeners into the JFrame?
- by A.K.
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
}
};