在MATLAB GUI中捕获键盘按键

时间:2012-11-28 12:35:53

标签: matlab radio-button matlab-figure matlab-guide

我正在使用matlab,我希望有单选按钮,并将一些键映射到它。

以下代码适用于显示单选按钮和从用户获取值。有人可以帮助我映射女性和女性2的关键字。

hgen_radio = uibuttongroup('visible','on','Units','pixels','Position',[1750 1045 170,50],'Title','Gender');
set(hgen_radio,'SelectionChangeFcn',@isMale_Callback);
ugen0 = uicontrol('Style','Radio','String','Male',...
    'pos',[10 5 50 25],'parent',hgen_radio,'HandleVisibility','off');
ugen1 = uicontrol('Style','Radio','String','Female',...
    'pos',[70 5 70 25],'parent',hgen_radio,'HandleVisibility','off');
set(hgen_radio,'SelectedObject',[]);

提前致谢!

1 个答案:

答案 0 :(得分:0)

在MATLAB中,按键必须由包含UICONTROL的数字捕获,然后传递。这是一个简单的方法。

hgen_radio = uibuttongroup('visible','on','Units','Normalized','Position',[.2 .2 .2 .2],'Title','Gender');
set(hgen_radio,'SelectionChangeFcn',@(x,y)disp('Clicked!'));
ugen0 = uicontrol('Style','Radio','String','Male',...
    'pos',[10 5 50 25],'parent',hgen_radio,'HandleVisibility','off');
ugen1 = uicontrol('Style','Radio','String','Female',...
    'pos',[70 5 70 25],'parent',hgen_radio,'HandleVisibility','off');
set(hgen_radio,'SelectedObject',[]);

set(gcf,'keypressFcn',@(x,y)catchKey(hgen_radio,x,y))

其中catchKey.m类似于:

function catchKey(hgen_radio,varargin)

switch varargin{2}.Key
    case {'1','2'}
        %to do: check if previous value was female, or male...
        feval(get(hgen_radio,'SelectionChangeFcn'))
    otherwise
        %pass other keypresss through
end

有关其他示例,请参阅:http://www.mathworks.com/matlabcentral/answers/1450

对于任何复杂的应用程序,你不应该像我上面那样传递句柄;而是使用setappdata和getappdata存储APPDATA中所有句柄的值。这大大澄清了很多代码。例如http://www.mathworks.com/help/matlab/ref/setappdata.html