You might not want to add a KeyListener
on a JLabel
. It would be better if you would add it to the JFrame
.
Supposing you have the following code structure, then it should work:
public class MyFrame extends JFrame {
private JLabel jLab;
//...fields, getters, setters whatever...
private int i;
public MyFrame()
{
i = 0;
jLab = new JLabel("Example");
addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent ke) {
//doSomething(); - this may create confusion.
}
@Override
public void keyReleased(KeyEvent ke) {
//doSomething(); - this may create confusion.
}
@Override
public void keyTyped(KeyEvent ke) {
doSomething();
}
});
add(jLab);
pack();
setVisible(true);
}
private void doSomething() {
i++;
jLab.setText(i + "");
}
}
And, don't forget to import
!
import javax.swing.*;
import java.awt.event.*;
RESULT: when you create a new MyFrame
in the main()
method. This is what you see at first:
After five random key-strokes,