how to get which button was pressed?

조회 수: 18 (최근 30일)
Stepan Vecera
Stepan Vecera 2021년 5월 4일
편집: Adam Danz 2021년 5월 5일
im trying to recreate minesweeper. i have array of buttons, and now i want to know, whitch button was pressed(so i can look around it, to know how many bomb are around).
this is how i create the array
w=9;
h=9;
setappdata(fig, 'fieldSize', [w, h]);
fS = getappdata(fig, 'fieldSize');
str.txtObj = gobjects(fS);
for iR=1:w
for iC = 1:h
button(iR, iC) = uicontrol(panel, ...
'Style', 'pushbutton', ...
'Units', 'normalized', ...
'Position', [(iC-1)*1/fS(2), 1-iR*1/fS(1), 1/fS(2), 1/fS(1)], ...
'String', ' ', ...
'Callback', @buttonPushed, ...
'Tag', ' ');
end
end

답변 (2개)

Adam Danz
Adam Danz 2021년 5월 4일
The first input to the buttonPushed callback function is the object handle to the button that was pushed. The object handles is also in the second input in event.Source where event is the name of the 2nd input.
If you need additional methods to ID the button, you can assign a tag property to each button and access the tag from within the callback function.

Jan
Jan 2021년 5월 4일
편집: Jan 2021년 5월 4일
You can provide the index as additional argument of the callback:
'Callback', {@buttonPushed, iR, iC}, ...
function buttonPushed(ButtonH, EventData, iR, iC)
end
Or you store the array button in the figure:
for iR=1:w
for iC = 1:h
button(iR, iC) = uicontrol(panel, ...
...
end
end
setappdata(fig, 'button', button);
function buttonPushed(ButtonH, EventData)
fig = ancestor(ButtonH, 'figure');
button = getappdata(fig, 'button');
[iR, iC] = find(ButtonH == button);
  댓글 수: 4
Stepan Vecera
Stepan Vecera 2021년 5월 5일
편집: Stepan Vecera 2021년 5월 5일
ive done it completely differ way, i calculated how many bombs are around it with two for loops right after i placed the bombs and placed the number in button.Tag, and then when the button is pressed i simply rewrite it from Tag to button.String. its not very pretty, but it gets the job done
Adam Danz
Adam Danz 2021년 5월 5일
편집: Adam Danz 2021년 5월 5일
That sounds like what my answer suggests. " you can assign a tag property to each button and access the tag from within the callback function"

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

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by