Well here are a few things to keep in mind.
1. You have to implement the KeyListener class
2. You have to add a KeyListener to a component [maybe the main frame]
3. Make sure the instance variable is initialized
4. Make sure you change the variable to something different other than what it was initialized to.
5. If your using the key to update a text value in a component, make sure you repaint the component.
Since you didn't provide the entire class, I cant check for these. But here is a small demo I just created.
Code:
package net.codecall.forums;
import java.awt.Dimension;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class ButtonListener implements KeyListener{
//Instance Variable
private int i = 0;
private JLabel label;
public ButtonListener() {
//create a new JFrame
JFrame frame = new JFrame("Key Listener");
//set the dimensions
frame.setPreferredSize(new Dimension(200, 200));
/****** ADD AN ACTION LISTENER TO THE FRAME ******/
frame.addKeyListener(this);
//create a new JLabel
label = new JLabel();
//set the text on the label
label.setText(String.valueOf(i));
//add the label
frame.add(label);
//make the frame visible
frame.setVisible(true);
//set the default close operation
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
//pack the frame
frame.pack();
}
public void keyPressed(KeyEvent e) {
//If the key D was pressed
if(e.getKeyCode() == 68){
//increase i by one
i++;
//'repaint' the label
label.setText(String.valueOf(i));
//and output the value to the console
System.out.println(i);
}
}
public void keyReleased(KeyEvent e) { }
public void keyTyped(KeyEvent arg0) { }
public static void main(String[] args){
new ButtonListener();
}
}