How do I use the Edit Text box in a GUI to define variables and structure fields in another function?

What I am trying to do seems simple but I cannot figure it out. Lets say I have variable A in a function. How do I make whatever I enter in a text box define variable A? Same thing with defining fields in a structure, how can I use the edit text box to define them?

Answers (1)

Hi Hector De La Torre,
here a solution I gave for a different question which passes handles to (possibly external) callback functions ( Can I modify inputs for pushbutton callback, answer by Jan shows another solution possibility):
Example 1
function mytest
GUI.a = 1;
GUI.fh = figure;
GUI.h1 = uicontrol('style','Edit',...
'string','1',...
'Units','normalized',...
'Position',[0.1 0.8 0.8 0.2],...
'backgroundcolor','w',...
'Tag','EditField');
GUI.h2 = uicontrol('style','Edit',...
'string','XX',...
'Units','normalized',...
'Position',[0.1 0.1 0.8 0.2],...
'backgroundcolor','c',...
'Tag','EditField2',...
'Enable','off');
GUI.h3 = uicontrol('Style','PushButton',...
'String','Disp a2',...
'Units','normalized',...
'Position',[0.1 0.4 0.8 0.15],...
'callback',{@func_compute,GUI.h1,GUI.h2},...
'backgroundcolor',...
'r','FontSize',12);
end
function func_compute(~,~,InHandle,OutHandle)
a = str2double(InHandle.String);
b = a * a;
OutHandle.String = num2str(b);
end
The input of first Edit-Field is used to calculate the square of itself and is displayed in a result field.
Another possibility is to use "global" variables in the context of GUI (nested) functions:
Example 2
function mytest2
GUI = struct;
GUI.a = 1;
GUI.fh = figure;
GUI.h1 = uicontrol('style','Edit',...
'string','1',...
'Units','normalized',...
'Position',[0.1 0.8 0.8 0.2],...
'backgroundcolor','w',...
'Tag','EditField');
GUI.h2 = uicontrol('style','Edit',...
'string','XX',...
'Units','normalized',...
'Position',[0.1 0.1 0.8 0.2],...
'backgroundcolor','c',...
'Tag','EditField2',...
'Enable','off');
GUI.h3 = uicontrol('Style','PushButton',...
'String','Disp a2',...
'Units','normalized',...
'Position',[0.1 0.4 0.8 0.15],...
'callback',{@func_compute},...
'backgroundcolor',...
'r','FontSize',12);
function func_compute(~,~)
GUI.a;
GUI.a = str2double(GUI.h1.String);
b = GUI.a * GUI.a;
GUI.h2.String = num2str(b);
end
end
Kind regards,
Robert

Categories

Find more on Creating, Deleting, and Querying Graphics Objects in Help Center and File Exchange

Products

Release

R2017b

Tags

Asked:

on 14 May 2018

Edited:

on 15 May 2018

Community Treasure Hunt

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

Start Hunting!