keyListener isn't working for me
in an applet i made with a KeyListener and a MouseListener,
my keyListener will not respond to keys pressed.
the mouseListener works fine.
the keyTyped, keyPressed, and keyReleased methods just won't get called.
can someone please find my mistake?
Code:
public class Cursor extends JApplet implements MouseListener, KeyListener{
BooleanJLabel[][] grid = new BooleanJLabel[5][5];
Icon backgroundIcon = new ImageIcon(Cursor.class.getResource("images/background.gif"));
Icon cursorIcon = new ImageIcon(Cursor.class.getResource("images/cursor.gif"));
Icon exclamationIcon = new ImageIcon(Cursor.class.getResource("images/exclamation.gif"));
Icon bothIcon = new ImageIcon(Cursor.class.getResource("images/both.gif"));
int cursorX = 0;
int cursorY = 0;
public void init(){
setSize(250, 250);
setLayout(new GridLayout(5,5));
for(int countY = 0; countY <5; countY++){
for(int countX = 0; countX <5; countX++){
BooleanJLabel background = new BooleanJLabel(backgroundIcon);
background.addMouseListener(this);
grid[countY][countX] = background;
add(background);
}
}
addKeyListener(this);
}
public void mouseClicked(MouseEvent m) {
}
public void mouseEntered(MouseEvent m) {
int x = ((JLabel)m.getSource()).getX()/50;
int y = ((JLabel)m.getSource()).getY()/50;
cursorX = x;
cursorY = y;
if(grid[cursorY][cursorX].isActivated()){
grid[cursorY][cursorX].setIcon(bothIcon);
}else{
grid[cursorY][cursorX].setIcon(cursorIcon);
}
}
public void mouseExited(MouseEvent m) {
int x = ((JLabel)m.getSource()).getX()/50;
int y = ((JLabel)m.getSource()).getY()/50;
if(grid[cursorY][cursorX].isActivated()){
grid[y][x].setIcon(exclamationIcon);
}else{
grid[y][x].setIcon(backgroundIcon);
}
}
public void mousePressed(MouseEvent m) {
}
public void mouseReleased(MouseEvent m) {
if(m.getButton()==MouseEvent.BUTTON1){
grid[cursorY][cursorX].switchActivated();
if(grid[cursorY][cursorX].isActivated()){
grid[cursorY][cursorX].setIcon(bothIcon);
}else{
grid[cursorY][cursorX].setIcon(cursorIcon);
}
}
}
public void keyPressed(KeyEvent k) {
}
public void keyReleased(KeyEvent k) {
}
public void keyTyped(KeyEvent k) {
grid[4][4].setIcon(exclamationIcon);
}
}