How to use the keyListener

i’m a bit confused by the keylistener.
i have my main component, a window. it contains a second component, a circle. i want my circle to “do” something, when a key is pressed.
so i made the main component a keyListener, and added the function

	bool keyPressed (const KeyPress &key, Component *originatingComponent)
	{
		myCircle->do();
		return 0;
	}

and added

myCircle->addKeyListener(this); in the constructor of my main component.
but this does not work.

but it does work, when i try it with mouselistener instead (and it’s corresponding button down function).
why is this so?

thanks!

setWantsFocus( true ); // ?

i set that and checked, that my main component has keyboard focus.
but it seems that the KeyPressed function never gets called. who is supposed to call it?
is there maybe an easy example of the function of keylistener in the juce examples?

It should be pretty simple, I am assuming that “x” class is the one interested in receiving keypress callback when keys are pressed and that it is the component being displayed.

Derive x from “KeyListener” and implement “bool keyPressed(const juce::KeyPress &key,juce::Component * originatingComponent);”

that should solve the problem.

[quote=“vishvesh”]It should be pretty simple, I am assuming that “x” class is the one interested in receiving keypress callback when keys are pressed and that it is the component being displayed.

Derive x from “KeyListener” and implement “bool keyPressed(const juce::KeyPress &key,juce::Component * originatingComponent);”

that should solve the problem.[/quote]

hi! yes this did work out. i don’t know why i have overseen this way (which seems to be the most intuitive way now too) so thank you for pointing my nose to the right direction!

[quote=“haesslich”]
hi! yes this did work out. i don’t know why i have overseen this way (which seems to be the most intuitive way now too) so thank you for pointing my nose to the right direction![/quote]

It’s a pleasure to be of little help. :slight_smile:

Does KeyListener work in VST editor?

I tried the following, but the keyPressed is never invoked.

class JuceDemoPluginAudioProcessorEditor : public AudioProcessorEditor, public KeyListener

bool JuceDemoPluginAudioProcessorEditor::keyPressed(const KeyPress &k, Component *c) { if(k == KeyPress::spaceKey) { } return true; }

If you just create a KeyListener, nothing will happen. You have to actually register it with a component to receive callbacks.

This did not work

but this worked

getTopLevelComponent()->addKeyListener(this);

1 Like

Hmm… This didn’t work for me. Neither did any of the above. Odd

Aha! Just noticed the following in this discussion: Can't get keyListener to work

setWantsKeyboardFocus(true);

That did the trick