Rahul Tripathi
Rahul Tripathi

Reputation: 555

How to perform Key Listener on SWT Label

KeyListener is not performed on Label. Please help any one? Below is Code snippet:

breakNodeLabel = new Label(this, SWT.WRAP);
breakNodeLabel.setBackground(new Color(getDisplay(), 204, 204, 204));
breakNodeLabel.addKeyListener(new KeyAdapter() {
    @Override
    public void keyPressed(KeyEvent event) {
    if (event.keyCode == SWT.DEL) {
        // deleteNode(this);
        System.out.println("------------Delete Break NODE----------------");
    }
    }
});

Upvotes: 0

Views: 942

Answers (2)

greg-449
greg-449

Reputation: 111217

Label does not support key events.

You could use a read only Text control instead:

new Text(this, SWT.READ_ONLY | SWT.WRAP);

Upvotes: 2

Kuba
Kuba

Reputation: 516

You've added KeyListener to Label. Label must have focus to get events.

If you want to listen for keyboard events in your whole window then add KeyListener to your shell:

shell.addKeyListener(new KeyAdapter()...

If you want global KeyListener add display filter:

Listener listener = new Listener() {

    @Override
    public void handleEvent(Event e) {
        if(e.type == SWT.KeyDown||e.type == SWT.KeyUp) {
            System.out.println("" + e.keyCode);
        }
    }
};
display.addFilter(SWT.KeyDown, listener);
display.addFilter(SWT.KeyUp, listener);

Upvotes: 1

Related Questions