You are now following this question
- You will see updates in your followed content feed.
- You may receive emails, depending on your communication preferences.
GUI Edit Text Box Value Check
8 views (last 30 days)
Show older comments
During runtime I want my GUI to confirm there are values in 4 edit boxes before the user can continue filling out the 5th edit box.
The edit box values will be of numbers and not strings.
To do this I want to input code in the edit box 5 callback. Something like (pseudo-code):
if editbox1 & editbox2 & editbox3 & editbox4 isempty
listbox3 = 'All boxes in first section not populated'
else
end.
How do the edit boxes hold their values? I assume they are of the type string.
Do I need to create and array(vector), populate the array with values (string, number or Boolan value), convert said values in the array from string to numbers, check population and keep the values of type number or, can the if statement compare the 4 edit boxes in sequence to check population and use the values as type number?
Accepted Answer
Jan
on 14 Mar 2016
Edited: Jan
on 19 Mar 2016
You can insert the check in the callbacks of the first 4 edit fields. The callbacks can check the validity of the contents at first:
% In the OpeningFcn: [EDITED, was CreateFcn]
handles.EditOk = false(1, 4);
set(handles.Edit5, 'Enable', 'off');
...
guidata(ObjectH, handles); % [EDITED] Store handles in the figure
function Edit1_Callback(ObjectH, EventData)
handles = guidata(ObjectH);
Str = get(ObjectH, 'String');
Value = sscanf(Str, '%f', 1);
if ~isempty(Value) && ~isnan(Value)
StrNew = sprintf('%.8g', Value); % In the wanted format
if ~strcmp(Str, StrNew)
set(ObjectH, 'String', StrNew);
% Perhaps a warning message?
end
handles.EditOk(1) = true;
else
handles.EditOk(1) = false;
end
if all(handles.EditOk)
set(handles.Edit5, 'Enable', 'on');
else
set(handles.Edit5, 'Enable', 'off');
end
guidata(ObjectH, handles); % [EDITED] Store handles in the figure
The same can be applied in all 4 edit fields - or you can use the same callback for all fields and some further trick to identify the index of the edit box.
Now the 5th edit field is activated only if the 4 edit boxes contain valid values.
24 Comments
Jay
on 16 Mar 2016
Thanks Jan,
I can not figure out where to implement the
% In the CreatFcn:
handles.EditOk = false(1, 4);
set(handles.Edit5, 'Enable', 'off');
code.
During runtime, the handles.EditOk vector reverts the previous columns element back to false (0).
i.e.
[1];[0,1];[0,0,1];[0,0,0,1].
Jay
on 18 Mar 2016
Edited: Jay
on 29 Mar 2016
I have since changed the location of the
handles.EditOk = false(1, 4);
set(handles.Edit5, 'Enable', 'off');
to the m files OpeningFcn rather than the edit CreateFcns which initialises as it is supposed too. 29/03/2016 No longer initialises as it once did.
I have some questions regarding the Edit1_Callback code you have written so that I can further understand the coding used.
1). Is there any particular reason why you changed the object handle specifier from hObject to ObjectH (is ObjectH intended to be used along side with hObject in the code or used as equivalent to) ?
2). When using the generic hObject (instead of the ObjectH) specifier in the Callbacks I receive a runtime error that there are too many input arguments. Why is this? Cant Callbacks execute nested if statements?
3). Is there a way to set blocks (ranges) of handles to be selected or does one have to individually select them?
I.e.
handles.EditOk = false(1,5)
set(handles.edit6 to handles.edit20, 'enable', 'off')
then
populate each edit Callback function (1 to 5) with if statement for true or false
then at function edit6 Callback
if all(handles.EditOk)
set(handles.edit6 to handles.edit20, 'enable', 'on')
else
set(handles.edit6 to handles.edit20, 'enable' 'off')
end
As the 2nd and 3rd questions directly relate to the OP I did not want to start a new thread (easier to use existing examples thus keeping with the same format).
Should one start a new thread to isolate related questions as it is easier for other users to reference in the future or should one keep an existing thread as it is directly related to an existing issue?
Jan
on 19 Mar 2016
I've edited my code and inserted some lines to makle it more clear.
@Justin: 1. It does not matter if you call the first input "hObject" or "ObjectH", it is just a matter of taste. I never work with GUIDE due to its limitations and incompatibilities between the Matlab releases. Therefore I forgot, how GUIDE calls the handle of the object.
2. Using another name for the first input cannot cause the error concerning the number of inputs. Perhaps you define the callback by
... 'Callback', {@Edit1_Callback, handles}, ...
such that it is called with 3 inputs. Then teh 3rd input might be the "handles" struct as it exists during the creation of the GUI. But "handles" is obtain dynamically also using guidata providing it as input is not useful - but this might be a question of taste also.
3. "handles.edit6 to handles.edit20" is not possible. It is simply a bad programming style to hide an index in the name of a field. What a pitty that GUIDE does this as default. Ugly!
Better use an array, e.g. created in the opening function:
handles.EditH = [handles.edit1, handles.edit2, ...and so on]
(Of course you can call it "handles.hEdit" also if you like). Then:
set(handles.EditH(6:20), 'enable', 'on')
Image Analyst
on 28 Mar 2016
Double click on the edit field in GUIDE. Look at the "tag" property. It does not say edit5. Repeat for all edit fields. If you want one called edit5, you need to have the tag "edit5" on one of the edit fields.
One other option is that you have a clear, clear all, or clearvars in your OpeningFcn().
I often set properties in the OpeningFcn(). Under rare circumstances, I need to do it in the OutputFcn() instead, which gets executed upon launch right after OpeningFcn(), and on shutdown of the app. If you definitely have an edit field with the edit5 tag, and there is no clear in the OpeningFcn(), then try putting the code in the OutputFcn().
Jay
on 29 Mar 2016
Edited: Jay
on 29 Mar 2016
I deleted the respective comment regarding the error as I could not unselect the 'Accepted Answer'.
I then realised you commented on the deleted comment.
The tag naming are indeed of the same structure as listed (edit1, edit2, ..... , editn). There are also no capitals in the naming convention.
I have attached the OpeningFcn code as their are no clear commands that I can see:
% --- Executes just before StarReduction is made visible.
function StarReduction_OpeningFcn(hObject, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to StarReduction (see VARARGIN)
% Choose default command line output for StarReduction
handles.output = hObject; % Creates array with all handle names and values
% Update handles structure
guidata(hObject, handles);
% DESCRIPTION:
% guidata(object_handle,data) stores the variable data as GUI data. If object_handle is not a figure handle, then the object's parent figure is used.
% data can be any MATLAB® variable, but is typically a structure, which enables you to add new fields as required.
%guidata can manage only one variable at any time. Subsequent calls to guidata(object_handle,data) overwrite the previously created version of GUI data.
% UIWAIT makes StarReduction wait for user response (see UIRESUME)
% uiwait(handles.figure1);
%%CODE GIVEN FROM MATLAB FORUM
% Initialize the handles logical array to be unable to populate
CURRENT SECTION OF CODE WORKING ON
handles.EditOk = false(1,4)
set(handles.edit5, 'Enable', 'off') % disables edit5 and EditOk = zeros(1,4)
% GUIDATA (): Stores or retrieves UI data
...
guidata(hObject, handles); % GUI pops up for data input
Please take no notice of extra comments used to describe what the code/ commands are actually doing.
GUI Tag
and
Respective M code
%
Image Analyst
on 29 Mar 2016
I'm not sure what the current problem is. What is not working? EditOk is just a field hanging off the handles structure, but you don't do anything with it, and nothing is going to happen automatically just because you set it equal to [false, false, false, false] - no effect to the GUI or anything. The edit5 text field/box should become disabled though.
Image Analyst
on 29 Mar 2016
OK, there's basically nothing in the callback, but so what? I still don't know what the problem is.
Jay
on 29 Mar 2016
Edited: Jay
on 29 Mar 2016
The problem is that GUI does not load (nor try to execute the sequential functions and Callbacks) and the following errors are shown due to the 'edit5' not being able to be referenced prior to being called.
I have tried substituting other handles to see if there was a specific error with the edit5 handle and the code still did not work.
I have updated my version to the latest so I can use the current syntax.
- Reference to non-existent field 'edit5'.
- Error in StarReduction>StarReduction_OpeningFcn (line 84) set(handles.edit5, 'Enable', 'off') % disables edit5 and EditOk = zeros(1,4)
- Error in gui_mainfcn (line 220) feval(gui_State.gui_OpeningFcn, gui_hFigure, [], guidata(gui_hFigure), varargin{:});
- Error in StarReduction (line 42) gui_mainfcn(gui_State, varargin{:});
It probably would have helped if I left the reference post.
In summary:
My issue is with the
set(handles.edit5, 'enable' , 'off')
Not being able to reference the edit5 handle during the OpeningFcn.
Is this due to edit5 being called prior to it being used? Does the OpeningFcn require a list of handles in order to be able to reference them prior to being called?
Image Analyst
on 29 Mar 2016
Is it possible you have two versions of either the m file or fig file and you're somehow still running the old one, or they're not matched up?
Just before that line where it fails, if you put handles, with no semicolon after it, what gets put into the command window. Paste it here. Or if you can, attach your .fig file and .m file.
handles % No semicolon, then look in command window.
Image Analyst
on 30 Mar 2016
Well there you go. You somehow destroyed handles. Put this also as the first line in the function and see where (what line) you actually blast over it and destroy it. It will happen somewhere in that StarReduction_OpeningFcn function. Just step through it one line at a time in the debugger until handles loses all its fields.
Jay
on 30 Mar 2016
The handles seem to be deleted prior to the function being invoked (i.e. not initiating any handles from the outset).
handles =
[]
where
handles: empty 0x0 double
=>
handles =
output: [1x1 Figure]
which is from the handles.output = hObject
=>
handles =
output: [1x1 Figure]
which is from guidata(hObject, handles)
=>
handles =
output: [1x1 Figure]
EditOk: [0 0 0 0]
from handles.EditOk = false(1,4)
I have created a temp GUI using guide for the sole purpose of comparing the varargout and OpeningFcn and the code has the same commands (apart from the handles.EditOk and set(handles.edit5, 'enable','off', which should have no effect as the handles are non-existent prior to them being run).
The Figures files functions are listed and tied to the M file so there is no confusion between which .fig file the M file is referencing.
I would like to find the cause of the figure referencing being skipped or deleted.
If I was to copy the master (previous version referencing correctly) and cut the commands from the current M file and paste them into the duplicated master I may run into a similar issue.
The only function preceding the OpeningFcn is the varargout function. Could something in there be causing the handles not to be able to be referenced?
Jay
on 30 Mar 2016
Edited: Jay
on 30 Mar 2016
The errors coming up are:
- Reference to non-existent field 'edit1'.
- Error in StarReduction>StarReduction_OpeningFcn (line 103) set(handles.edit1, 'enable', 'off') % disables edit5 and EditOk = zeros(1,4)
- Error in gui_mainfcn (line 220) feval(gui_State.gui_OpeningFcn, gui_hFigure, [ ], guidata(gui_hFigure), varargin{:});
- Error in StarReduction (line 42) gui_mainfcn(gui_State, varargin{:});
When trying to independently run (gui_mainfcn.m) the
gui_mainfcn(gui_State, varargin)
has the following error:
this leads me to believe something is awry in the gui_mainfunction code.
Jan
on 30 Mar 2016
You see, that you cannot run the gui_mainfcn independetly, because it requires inputs.
As far as I understand the handles struct is empty inside your OpeningFcn. Did you try to obtain the current value of this struct instead of using the value from the inputs?
function StarReduction_OpeningFcn(hObject, handles, varargin)
handles = guidata(hObject);
handles.output = hObject;
...
Jay
on 30 Mar 2016
Edited: Jay
on 30 Mar 2016
Fantastic!!!!
The code now initializes as it should.
Does the function varargout = filename_OutputFcn
Varargout {1} = handles.output
output a value at the end of running of the code?
In other words, is this function used to run an algorithm once all relevant fields are populated in the GUI?
I am receiving an error that the 'output' field does not exist. I am not sure to delete it as it is part of the initial code used to create the M file structure tied to the GUI (.fig file).
Image Analyst
on 30 Mar 2016
Like Jan said, you cannot run a function inside of a huge m-file by itself without supplying inputs. And the OpeningFcn is the worst one for you to pick. We had no idea until now that you were doing that instead of the usual ways of typing F5 or clicking the green Run Triangle on the tool ribbon like everyone else. Let us know where you heard that you should do that, and we'll try to squash that.
Anyway, I'm now assuming that you learned to click the green run triangle or type F5 and it's working. But no, you don't have to have the OutputFcn return anything. You can have
function filename_OutputFcn
and it might work. The problem was you were trying to return it without assigning it, so just don't return it if you don't want to use it. I say might work because we are still really confused as to why the code you copied says
function varargout = filename_OutputFcn
instead of
function varargout = StarReduction_OutputFcn
That could lead to a problem. Make sure that the prefix of all the callbacks match each other or else you will probably get into trouble.
Jay
on 30 Mar 2016
I was using the green triangle "run" button to execute the program.
I found the gui_mainFcn when stepping through the sections of code and thought that may have been corrupted some how thus causing my problems.
As for the above code I used the "filename" specifier to be the same as "StarReduction". I see how that was a bad idea in hindsight.
When you say " Like Jan said, you cannot run a function inside of a huge m-file by itself without supplying inputs" can you please eloborate on what constitutes as input? Do you basically mean I have to specify what the handles represent before calling them?
As in: handles = guidata (hObject)
will then allow handles.hObject where hObject can be any existing handle to call?
Image Analyst
on 30 Mar 2016
Edited: Image Analyst
on 30 Mar 2016
Jan just saw
>> gui_mainfcn
in the command window and so we thought that you typed that in to run it, instead of clicking the green run triangle. So he just meant that you cannot do that.
This does not have to take 13 days to fix. If you want us to fix it, just attach the .m file and .fig file, and any data files needed to run it.
Image Analyst
on 31 Mar 2016
Justin, make line 125 in OutputFcn this:
varargout{1} = 1;
It will then launch without error.
Jay
on 4 Apr 2016
Does the
varargout{1} = 1;
Apply to all Callbacks? I.e. can the Callbacks only have one output?
If edit1_Callback has (hObject, eventdata) will that be the cause of the runtime error:
'Error using StarReduction>edit1_Callback Too many input arguments.'
The error is thrown when I populate edit1 in the GUI and select the edit2 box for population.
Walter Roberson
on 4 Apr 2016
No, the output function is not a callback. None of the callbacks can have outputs.
If you defined edit1_Callback to take only (hObject, eventdata) and you programmed this in GUIDE then you will get that error about too many input arguments, because GUIDE automatically adds code to fetch the handles structure and add it as the third parameter. Do not mix programming styles: if you are using GUIDE then use the GUIDE three-input style, and if you are coding your own callbacks, expect only two inputs unless you coded otherwise.
More Answers (1)
Image Analyst
on 18 Mar 2016
Maybe something like this (if using R2014b or later) (off the top of my head, untested)...
edit1Number = str2double(handles.edit1.String);
% Check for a non-empty edit box and a valid number (no letters or symbols).
if isempty(handles.edit1.String) || isnan(edit1Number)
% They didn't enter a number.
% They entered a character, symbols, or something else not allowed.
% Assign some default and notify the user.
edit1Number = defaultValue;
message = sprintf('I said it had to be a number.\nI will use %.2f and continue.', usersValue1);
uiwait(warndlg(message));
% Put it into the text box too, replacing their bad entry.
handles.edit1.String = num2str(edit1Number);
end
Repeat for validation of the other edit text boxes.
4 Comments
Jay
on 19 Mar 2016
Thanks Image Analyst,
I have implemented the following code with the edit1_Callback
Edit1Number = str2double(handles.edit1.string)
if isempty(handles.edit1.string) || isnan(Edit1Number)
Edit1Number = 0
message = sprintf('No Value Inputed!!! Must input value to continue')
% Have listbox1 show message value
uiwait(warndlg(message))
handles.edit1.string = num2str(Edit1Number)
end
During runtime I am getting the following errors:
153 Edit1Number = str2double(handles.edit1.string)
Attempt to reference field of non-structure array.
Error in StarReduction>edit1_Callback (line 153)
Edit1Number = str2double(handles.edit1.string)
Error in gui_mainfcn (line 96)
feval(varargin{:});
Error in StarReduction (line 42)
gui_mainfcn(gui_State, varargin{:});
Error in
@(hObject,eventdata)StarReduction('edit1_Callback',hObject,eventdata,guidata(hObject))
Error while evaluating uicontrol Callback
153 is the line number.
Can you please explain why and how each of the errors are attributed?
Also is there any reason why it has to be 2014 or later? Is that because that is what you use or have there been major changes in the way the functions are executed in the core program?
I.e. is it imperative for me to upgrade to run recent examples of code without running into syntax errors?
Image Analyst
on 19 Mar 2016
I used the syntax from the last several versions. If you have an older version, you need to use the syntax Jan gave above.
See Also
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!An Error Occurred
Unable to complete the action because of changes made to the page. Reload the page to see its updated state.
Select a Web Site
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .
You can also select a web site from the following list
How to Get Best Site Performance
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.
Americas
- América Latina (Español)
- Canada (English)
- United States (English)
Europe
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)
Asia Pacific
- Australia (English)
- India (English)
- New Zealand (English)
- 中国
- 日本Japanese (日本語)
- 한국Korean (한국어)