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 Center および File ExchangeVisual Exploration についてさらに検索

製品


リリース

R2016b

Community Treasure Hunt

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

Start Hunting!

Translated by