Keypress event?

Please, help!
I can not create a function that controls an object when I press a button on the keyboard. Does not work
R = new DrawableImage();

R->setBounds(0, 200, 10, 10);

bool MainComponent::keyPressed(const KeyPress &key, Component* originatingComponent)
if (key.downKey) {

	R->setBounds(0, 300, 10, 10);
return 0;

I do not understand how to link my object to the originatingComponent

Hi @natali1968 ,
other than mouseEvents, that happen on a certain position on the screen, keyboard events have no visual context, where they belong to. So it would be problematic, if all components would receive all key events.
There is a paradigm called keyboardFocus, that is always associated with ONE component, that receives the key events.
Usually components gain focus, when they were clicked.
You can switch on and off, if a component wants the focus or not: Component::setWantsKeyboardFocus (true);
or programmatically give the focus to a component: Component::grabKeyboardFocus()

Apart from that, the code you wrote should work.
Note, that every Component is already a keyboardListener, so overriding Component::keyPressed() has already the effect without adding it as listener, as long as the Component has the focus.

1 Like

none of that setKeyboardFocus/GrabKeyboardFocus is necessary to intercept key presses:

see the 3-function example code at the end of the above post for all you need to capture keyPress events.


Excuse me, matkatmusic, I did not understand where to look an example

In general, the documentation is quite complete, but there are absolutely no examples of use. This greatly complicates the work of inexperienced developers like me


Oh, sorry, I found it, thanks!


Click the linked post in my reply to daniel to see the example code I was talking about.