How do I ignore double clicks in my GUI buttons?

13 visualizaciones (últimos 30 días)
I have created a GUI containing a button that performs a callback. Sometimes, users accidentally double-click the button, causing the callback to fire twice. How do I stop that?

Respuesta aceptada

MathWorks Support Team
MathWorks Support Team el 5 de Mzo. de 2021
Editada: MathWorks Support Team el 5 de Mzo. de 2021
MATLAB UI buttons do not offer support for double-clicking. However, you can implement a mechanism that ignores the second click.
As an example, here is a function that implements such a mechanism. This function makes use of a persistent variable, "check", to count the number of recent clicks. If there are no recent clicks, then the single-click action is executed. However, if there are recent clicks, new clicks are ignored for a short period of time.
function pushbutton1_Callback(hObject, eventdata, handles)
persistent check % Shared with all calls of pushbutton1_Callback.
delay = 0.5; % Delay in seconds.
% Count number of clicks. If there are no recent clicks, execute the single
% click action. If there is a recent click, ignore new clicks.
if isempty(check)
check = 1;
disp('Single click action')
else
check = [];
pause(delay)
end
end
The trick here is to define "check" as a persistent variable, which means that its value doesn't get cleared after the function has stopped executing, but it persists through all calls to this function. This makes it possible to track the number of (recent) calls to this function, effectively identifying double clicks.
You can find more examples on how persistent variables work in MATLAB in the following documentation page:
  1 comentario
Allen
Allen el 21 de Feb. de 2018
I have used the method provided by the MathWorks Support Team and still have the code for my pushbutton GUI execute each time on a multi-click by the user. However, a slight edit to their code does the trick. See example below:
function pushbutton1_Callback(hObject, eventdata, handles)
persistent check % Shared with all calls of pushbutton1_Callback.
% Count number of clicks. If there are no recent clicks, execute the single
% click action. If there is a recent click, ignore new clicks.
if isempty(check)
check = 1;
disp('Single click action')
else
% Ends Callback execution if pushbutton is clicked again before
% Callback has completed.
return
end
% -----Callback function code----- %
% Resets the 'check' variable for additional use of the Callback function
check = [];
end

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Interactive Control and Callbacks en Help Center y File Exchange.

Productos


Versión

R2016b

Community Treasure Hunt

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

Start Hunting!

Translated by