I'm having a bit of trouble with Matlab's uicontrol handling. Here's the situation:
My (programmatic) GUI contains an editable text field. This field originally contains a numeric value and is supposed to always contain one. In order to ensure that, the 'String' parameter is to be repeatedly checked, converted to numeric, and re-entered into the 'String' property of the uicontrol. This is supposed to happen whenever a user enters a visible character into the text field.
Additionally, the program is supposed to notice at any point whether the current value of said text field differs from the original value, which is stored in memory. If the user closes the figure, a modal dialog opens and asks if he wants to save the change to that value or discard it. If the figure is then reopened (through the rest of the GUI), the value of the text field starts out as either the same it started out as before (if the user discarded the changes) or the changed value defined by the user.
Both of these things fail in some instances because of a strange behaviour: The uicontrol's 'String' property is only updated after the uicontrol loses focus. This is not a problem if the user wants to do other things on that GUI or knows how to handle this. I can also live with my text field only updating to a meaningful numeric value after it loses focus.
The problem is, when I close the figure via Windows' red X button in the top right corner after changing the value of the text field, but without first clicking somewhere else, the 'String' value is never updated, so the CloseRequestFcn doesn't notice the change and simply closes the window. Even pausing for a whopping 100ms and then explicitly calling the text field's Callback from within the CloseRequestFcn doesn't help, it just closes without my dialog. The reverse is also true, if I do change the value, click somewhere else, and then change it back, it will display the dialog unless I first click somewhere else again.
So the question is this: How do I ensure the uicontrol correctly updates/executes its Callback when I click the red X button provided by Windows?
And bonus question: How do I execute this Callback "on the fly" in order to correct any impossible values the user enters as soon as he does (e.g. letters other than e and i)?
Here's the isolated part of my GUI that causes the problem, copy into a file called 'guitest.m' and run in order to test what I'm talking about.
function guitest
changed = false; %// tracks changes to catch closing without saving
startval = 1; %// the starting value
handles.figure = figure('Resize','off','Toolbar','none','Menu',...
'none','Name','Change text field value','CloseRequestFcn',...
#closefig,'Visible','off'); %// not visible until fully created
handles.textfield = uicontrol('Style','edit','Units','normalized',...
'Parent',handles.figure,'String',startval,...
'Position',[.4 .6 .2 .1],'Callback',#changedValue);
handles.button = uicontrol('String','Push me','Units','normalized',...
'Parent',handles.figure,'Position',[.4 .3 .2 .2],'Callback',#dispval);
%// all done, display GUI
set(handles.figure,'Visible','on');
%// callback functions
function closefig(~,~) %// Quit program
pause(0.1);
changedValue(handles.textfield); %// update fields
if changed
disp('Do you really want to close?'); %// save dialog
else
delete(handles.figure); %// this is used as CloseRequestFcn!
end
end
function changedValue(hObject,~)
newval = uint16(str2double(get(hObject,'String')));
changed = (startval ~= newval);
end
function dispval(~,~)
disp('With buttons inside the GUI, it works properly:');
disp(get(handles.textfield,'String'));
disp(changed);
end
end
Will forcing a GUI focus change with uicontrol in your closing function provide the correct behavior? From the documentation:
uicontrol(uich) gives focus to the uicontrol specified by the handle,
uich
For the 'bonus' you're likely going to have to leverage the underlying Java. See the article on editbox data input validation from Undocumented Matlab.
Related
I have been working on a project I should do in MATLAB Appdesigner. What I am trying to do is when the Switch button is pressed, the value of the textbox changes to my desired value.(This just only a bit of the project, not all of it). For instance, as illustrated below, if the user clicks on the switch button to set it on Transient mode, the value in the textbox automatically changes to a specific number.
You have to add a callback to your switch button. Assuming the text field is called EditField and the switch is called Switch, this call back will change the EditField value to 10 every time you change it to Transient:
% Value changed function: Switch
function SwitchValueChanged(app, event)
value = app.Switch.Value;
if strcmp(value, 'Transient')
app.EditField.Value = '10';
end
end
Note that the value of the switch is whatever you wrote on the interface, so if you change Transient or Steady to something else, you will have to change your code. Also note that EditField.Value expects a char array.
I'm using MATLAB GUIDE to build a GUI to control a piece of hardware. I have a data table the user needs to fill, and every time they select a cell a new configuration is sent to the hardware. This is easily done using the CellSelectionCallback().
However, I also have a single reference value that is currently being entered into an edit textbox. I would like for the GUI to send a new configuration to the hardware whenever a user selects the textbox, but before they enter their new value. Is there a similar SelectionCallback function that can be used for the textbox? The best solution I've come up with is to create a 1x1 table instead of an edit box.
Your best bet is going to be to use a Java control since the standard MATLAB uicontrol does not have a focus callback. You can use a JTextField object, add it to your GUI with javacomponent and then register the FocusGainedCallback.
jtext = javax.swing.JTextField();
jtext.setHorizontalAlignment(javax.swing.JTextField.CENTER);
% Add the control to your GUI
htext = javacomponent(jtext, [10 10 200 10]);
% Register a callback to be executed when the box is selected
set(htext, 'FocusGainedCallback', #yourCallback)
Basically I have a really complex Matlab GUI, where the user can add different strings by an editextbox (the one you can type in). The problem is that I assigned different functions to different keyboard button pushdowns, for example 's' and 'e' are in use. Every time you try to type in for example 'snake' the functions assigned to 's' and 'e' are executed. Is there any way to determine wheter I clicked in the edittextbox, and it is in use -> like a logical value so i can block the keypressfunctions by checking it.
Within your callback, you can use gco to get the current object. You can then check if this is the graphics handle to your edit box.
fig = figure('WindowKeyPressFcn', #(s,e)keypress());
hedit = uicontrol('Style', 'edit');
function keypress()
if ~isequal(gco, hedit)
disp('Window Key Press')
end
end
If on the other hand you didn't set a global key press callback (using WindowKeyPressFcn) and you instead set the KeyPressFcn of each uicontrol individually, just specifying a different (or no) KeyPressFcn for the edit box would work.
How do I mimic a button click in matlab?
Simply excecuting the callback function doesn't work since within its callback it uses the gcbo command and I cannot alter the excecuting function. I furthermore would not like to shadow gcbo for obvious reasons.
In case it matters I look for a solution which works on matlab R2012a.
you can try calling the java.awt.Robot class, for example.
robot = java.awt.Robot;
pause(2) % wait some time
robot.keyPress (java.awt.event.KeyEvent.VK_ENTER); % press "enter" key
robot.keyRelease (java.awt.event.KeyEvent.VK_ENTER); % release "enter" key
read more about GUI automation using a Robot here...
I'm not sure this will work on Matlab R2012a, but it does on later versions.
gcbo only contain the button handle. If you have (or can retrieve/find) the button handle, just call the function callback with the button handle as first argument and an empty variable as the second argument.
something looking like that:
button_callback( buttonHandle , [] ) ;
The callback will not make any difference between gcbo or the button handle and will function exactly the same.
If you do not have the button handle in the first place, you can try to find it with findobj:
buttonHandle = findobj(gcf,'Style','PushButton','String','The Button Text')
Depending on how the GUI was built/defined, then handle visibility may not be immediately apparent, in which case you can search deeper with findall:
buttonHandle = findall(gcf,'Style','PushButton','String','The Button Text')
or may be the handle was nicely saved in the guidata structure:
handles = guidata(gcf) ;
and search the structure for what may be your button handle.
Note: in the last 3 examples above, make sure the GUI figure which contains the button has the focus before you call gcf, or better yet, replace gcf by the actual figure handle.
I have a GUI with an edit box and a push button on the tool bar (well, more things than that, but those are the only things that matter!) Anyway, I have it so when you press the push button tool a variable is set to equal the string in the edit box. A simple var = get(handles.edit1, 'string'). However, when I go straight from entering the value in the box to clicking the pushbutton (without clicking anywhere else or pressing return), var is assigned the previous value in the edit box. Why is this? Is there any way to make sure the push button tool will pick out the correct value?
The GUI was made using guide, if that matters.
This is happening because the uipushtool callback is executing before the text box has time to 'validate'. There is surely a more elegant way to do that but this trick works:
You can use the waitfor command to tell the uipushtool callback to wait for the editable box to validate its input. Unfortunately is is not exactly enough so we'll have to:
1) pass the focus to a dummy control (I created a dummy pushbutton named pushbutton1 which does nothing. The focus could be send to any other dummy control.
2) now wait for the text box to validate its content.
3) When the text box is done, then retrieve the content the traditional way.
This method requires:
- A dummy control to send the focus to (but you can use a real one too)
- An dummy (or not) callback function for your editable box. (the waitfor instruction will wait for the callback to finish, if there is no callback, it will error
function uipushtool1_ClickedCallback(hObject, eventdata, handles)
uicontrol( handles.pushbutton1 ) ; %// pass the focus to a dummy control
waitfor(handles.edit1,'String'); %// wait for the editable box to validate its content
var = get(handles.edit1, 'string') ; %// now retrieve the editable box content
set( handles.text1 , 'String' , var ) %// this can be deleted, just to verify the method
% --------------------------------------------------------------------
function edit1_Callback(hObject, eventdata, handles)
%// This is the dummy callback function for the editable box
%// Do absolutely nothing here (or do if you want ... your choice)
EDIT
as I feared, my initial solution was too dirty to be robust enough. With 2 (or more) textboxes, I tried a large number of things but without success. I dropped the waitfor, I noticed that in some case, when the uipushtool was pressed, the callback of the editbox would fire but the uipushtool would not execute at all ... so i tried to managed things directly from the editbox callback => from the editbox keypressedFcn send each character as we type to a variable ... but even this editbox callback doesn't know the content of the edit box at the time it is executed ?? (This link provide a very simple example to reproduce that).
So to my great own disappointment, I had to resort to an 'external' solution. (If you accept that it becomes very simple though). The trick is to retrieve the handle of the Java EditBox object. Once we have the handle, getting the "real time" content is just matter of converting the Java string into a Matlab string.
To retrieve the Java object handles, you need the function FindJObj from Matlab central.
Put that anywhere in your matlab path, then the code for your pushbutton become something like :
To make sure there was no interferences between the text boxes and the uipushtools I made 2 separate uipushtools each controlling 1 editbox
function uipushtool1_ClickedCallback(hObject, eventdata, handles)
jEditbox = findjobj(handles.edit1); %// get the handle of the java editbox #1
var = char(jEditbox.getText) ; %// retrieve Java string and convert it to matlab string
disp(['uipushtool1_ClickedCallback running. Textbox1 content = ' var ]) %// debug line, you can delete or comment that
% --------------------------------------------------------------------
function uipushtool2_ClickedCallback(hObject, eventdata, handles)
jEditbox = findjobj(handles.edit2); %// get the handle of the java editbox #2
var = char(jEditbox.getText) ; %// retrieve Java string and convert it to matlab string
disp(['uipushtool2_ClickedCallback running. Textbox2 content = ' var ]) %// debug line, you can delete or comment that
Thanks to Yair Altman for the findjobj function, and many other contributions for Matlab users.
I tried to replicate your problem and created a new GUI using guide with only a pushbutton and an edit field. If I set the button callback to:
function pushbutton1_Callback(hObject, eventdata, handles)
get(handles.edit1,'string')
it always prints the current value of the edit field, no matter if I click somewhere else after entering the value or not. Which version of Matlab are you using? I've tested it using Matlab 2010a.