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->addKeyListener(this);
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.
HTH
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