Can i add an image to an axes without a push button

2 views (last 30 days)
Hello, I'm trying to create a simple program that displays two images of which you have to choose from (by using keystrokes, but I'm not at that level yet) and I am trying to add an image to the axes, and I cant seem to figure out the right code without using a push button. How to I go about this?

Answers (1)

Brian Neiswander
Brian Neiswander on 13 Aug 2015
As Brendan mentioned, you can accomplish this using the "KeyPressFcn" property of the figure window. This property allows you to declare a callback function to run every time a key is pressed while the figure window has focus.
As a quick demonstration, you can create a new file named "keypressCallback.m". Inside this file, paste the following function:
function keypressCallback(hObject, eventdata)
%display which key was pressed
disp(['The key pressed was ' eventdata.Key '.']);
The function's two input arguments ("hObject" and "eventdata") are standard protocol for user interface callbacks. The variable "eventdata" is a structure:
eventdata =
Character: ' '
Modifier: {1x0 cell}
Key: 'leftarrow'
where the "Key" field contains a string describing the last key pressed. Within the callback function, you can access this string using:
Save the callback function and then open a new figure window with the "KeyPressFcn" set to use your callback function:
figure('KeyPressFcn', @keypressCallback);
When the figure window opens, start pressing keys on your keyboard and watch the output on the MATLAB console:
The key pressed was q.
The key pressed was return.
The key pressed was space.
The key pressed was downarrow.
The key pressed was rightarrow.
Now, you can change the code inside the callback function to perform specific tasks when certain keys are pressed.
For reference, I have included a link below with more information on using callback functions.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by