How to use the keyListener


#1

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!


#2

setWantsFocus( true ); // ?


#3

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?


#4

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.


#5

[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!


#6

[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:


#7

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; }


#8

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


#9

This did not work

but this worked

getTopLevelComponent()->addKeyListener(this);