Question

I have added JLabel on my JFrame object. I want to implement a key listener on JLabel. Can I implement it? If yes, how can I do that?

Was it helpful?

Solution

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:

Starting

After five random key-strokes,

After 5

OTHER TIPS

Guess I'm a bit too late but calling label.requestFocus(); after adding the key listener to the label works for me!

Key events are fired by the component with the keyboard focus when the user presses or releases keyboard keys.

BUT JLabel is not one of those components.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top