Save the output of a pushed button

9 views (last 30 days)
Fed
Fed on 2 Mar 2015
Commented: Adam on 3 Mar 2015
Hello everyone
I created several buttons within a figure using the uicontrol function. The subject, moving the mouse, has to press one button out of 6. Now, I would like to save which button the subject has chosen, but I have no idea how to do it.
Any help will be appreciated.
Thank you in advance!

Accepted Answer

Adam
Adam on 2 Mar 2015
Edited: Adam on 2 Mar 2015
fCallback = @(src,evt) disp( src.String );
figure; hButton1 = uicontrol( 'Units', 'normalized', 'Position', [0.1 0.1 0.35 0.1], 'Style', 'pushbutton', 'Tag', 'button1', 'String', 'Button 1', 'callback', fCallback );
hButton2 = uicontrol( 'Units', 'normalized', 'Position', [0.55 0.1 0.35 0.1], 'Style', 'pushbutton', 'Tag', 'button2', 'String', 'Button 2', 'callback', fCallback );
should give an example of what you want. It isn't necessary to set a Tag, but you can use either the tag or the string to determine which button was pressed if you do set a tag. My example ignores the tag and outputs the string, but strings are not guaranteed to be unique, although in your case I guess they will be.
Obviously you then need to save the information, but you haven't given any details as to what kind of code you are putting these into.
  3 Comments
Fed
Fed on 3 Mar 2015
Adam, I am not that good in Matlab therefore I can't check which is the output of the button pressed.
this is my code now. fCallback = @(src,evt) disp( src.String );
hButton1 = uicontrol( 'Units', 'normalized', 'Position', UL, 'Style', 'pushbutton','String', 'HAPPINESS','FontSize',16,'callback', fCallback ); hButton2 = uicontrol( 'Units', 'normalized', 'Position', DL, 'Style', 'pushbutton', 'String', 'SADNESS', 'FontSize',16,'callback', fCallback ); Since I want to check if the first button has been pressed I tried:
if hButton1.String=='HAPPINESS' answer = 'HAPPINESS' end but in the fields within hButton1 is written Error Display Value. Maybe I am just not understand properly. Can you help me? Thanks again
Adam
Adam on 3 Mar 2015
You will need to replace the callback I gave you with a normal function (i.e. not an anonymous function like that) that stores the result of which button was pressed somewhere. Where that value would be stored depends entirely on what you want to do with it and where this code is sitting - e.g. is it called from a function?
I can't see why your code would result in an error though even though it doesn't do what you would need it to.
hButton1.String will always be 'HAPPINESS' since that is what you created it as for the first button.
Incidentally, use strcmp( hButton1.String, 'HAPPINESS' ) to compare strings, not ==

Sign in to comment.

More Answers (0)

Categories

Find more on Interactive Control and Callbacks in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!