仅在编辑文本MATLAB GUI中输入数字



我在MATLAB GUI中有一个编辑文本。我希望用户能够只写数字,每当他们写一个文本字符时,最后一个字符会立即删除。此外,我不知道把这个代码放在哪种函数中(回调、按键等)

如果不使用Java,这是不可能的。这是因为MATLAB无法访问uicontrol类型的字符串;您只能访问其当前字符串(即,在按下Enter或更改焦点之后)。

以下是一个不完美的解决方法。它使用两个相同的编辑框,一个在另一个的顶部,但最顶部的框最初是隐藏的。可见编辑框的KeyPressFcn

  1. 仅在数字上过滤按键
  2. 在具有全局存储的字符串中累积有效按键
  3. 将该字符串设置为不可见编辑框的当前字符串
  4. 使不可见的编辑框可见,从而遮挡您正在键入的编辑框

它的CallBack功能然后是

  1. 获取通常不可见的框的字符串
  2. 将始终可见框的字符串设置为等于该字符串
  3. 再次隐藏通常不可见的框

以下是实现(从这里大量借用):

function GUI_tst
% Create new GUI
G.fh = figure('menubar' , 'none',...
'units'   , 'normalized', ...
'position', [.4 .4 .2 .2]);
% The actual edit box
G.eh1 = uicontrol('style'      , 'edit',...
'units'      , 'normalized', ...
'position'   , [.1 .4 .8 .2],...
'string'     , '',...
'KeyPressFcn', @kpr,...
'Callback'   , @cll);
% The "fake" edit box      
G.eh2 = copyobj(G.eh1, G.fh);
set(G.eh2, 'Visible', 'off');
% Its string (global)       
G.eh_str = '';

guidata(G.fh, G);
end

% "Real" edit box' KeyPressFcn()   
function kpr(~, evt)
if isempty(evt.Character)
return; end
G = guidata(gcbf);
% Occlude the "real" editbox with the "fake" one
set(G.eh2, 'visible', 'on');
% Accumulate global string if keys are numeric
if strcmp(evt.Key,'backspace')
G.eh_str = G.eh_str(1:end-1);
elseif isempty(evt.Modifier) && ...
any(evt.Character == char((0:9)+'0') )
G.eh_str = [G.eh_str evt.Character];        
end
% Set & save new string
set(G.eh2, 'string', G.eh_str);
guidata(gcbf,G);
end

% "Real" edit box' CallBack()   
function cll(~,~)    
G = guidata(gcbf);   
% Set the "real" box' string equal to the "fake" one's, 
% and make the "fake" one invisible again
set(G.eh1, 'String', get(G.eh2, 'String'));
set(G.eh2, 'visible', 'off');
end

这相当有效,但也有一些缺点:

  • 因为你在看不见的地方打字,所以光标被隐藏了
  • 选择文本并按退格键/删除键无效
  • 它的资源效率不是很高

尽管使用Java是可能的(请参阅MATLAB之神Yair Altman的这篇文章),但更简单、更常见的方法是接受用户输入的无效输入,只在Callback函数中检查/更正它(即,在按下Enter后)。

最新更新