In addition to using KeyListener (as shown by others' answers), sometimes you have to ensure that the JComponent you are using is Focusable. This can be set by adding this to your component(if you are subclassing):
@Override
public void setFocusable(boolean b) {
super.setFocusable(b);
}
And by adding this to your constructor:
setFocusable(true);
Or, if you are calling the function from a parent class/container:
JComponent childComponent = new JComponent();
childComponent.setFocusable(true);
And then doing all the KeyListener stuff mentioned by others.