How do I ignore double clicks in my GUI buttons?

조회 수: 13 (최근 30일)
MathWorks Support Team
MathWorks Support Team 2017년 1월 4일
편집: MathWorks Support Team 2021년 3월 5일
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?

채택된 답변

MathWorks Support Team
MathWorks Support Team 2021년 3월 5일
편집: MathWorks Support Team 2021년 3월 5일
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
Allen
Allen 2018년 2월 21일
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

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Interactive Control and Callbacks에 대해 자세히 알아보기

제품


릴리스

R2016b

Community Treasure Hunt

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

Start Hunting!

Translated by