Как получить предыдущее значение, введенное из функции обратного вызова?

StackOverflow https://stackoverflow.com/questions/2939285

Вопрос

Я знаю, что это, вероятно, простая проблема, но я новичок в Matlab GUI и в основном хочу получить старое значение, которое используется для хранения в текстовом поле для замены значения, которое только что было введено. Например

  1. Текстовое поле содержит допустимую строку,
  2. Пользователь вводит неверную строку,
  3. Callback Func, проверяет вход и реализует новый вход - это ошибка и возвращается к старому предыдущему значению.

Как это должно быть реализовано или сделано? ATM Я просто использую значения Get и Set свойств. Ниже приведен некоторый пример код:

function sampledist_Callback(hObject, eventdata, handles)
% hObject    handle to sampledist (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of sampledist as text
%        str2double(get(hObject,'String')) returns contents of sampledist as a double

input = str2double(get(hObject,'String'));
if(input < 0 || input > 500)
    errordlg('Sampled Dist. must be > 0 and < 500','Sample Dist - Input Error');
    set(handles.sampledist,'String',['10']); %<--- I would like this value 10 to be the previous entry!
    guidata(hObject,handles);
else
   set(handles.sampledist,'String',['',input]);
   guidata(hObject,handles);
end
Это было полезно?

Решение

Просто добавьте новое поле sampledistPrev к вашим обрабатам структуру.

в openingFcn графического интерфейса определяют свойство с такой же линией:

handles.sampledistPrev = 10; %# or whatever you choose as default value
%# if you want, you can set the default value to the GUI, so that you only need 
%# to change it at one point, if necessary, like so:
set(handles.sampledist,'String',num2str(handles.sampledistPrev));
%# don't forget to save the handles structure at the end of the openingFcn
guidata(hObject,handles)

Затем вы обновляете свой обратный звонок, как это:

function sampledist_Callback(hObject, eventdata, handles)
% hObject    handle to sampledist (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of sampledist as text
%        str2double(get(hObject,'String')) returns contents of sampledist as a double

input = str2double(get(hObject,'String'));
if(input < 0 || input > 500)
    errordlg('Sampled Dist. must be > 0 and < 500','Sample Dist - Input Error');
    set(handles.sampledist,'String',num2str(handles.sampledistPrev)); %reset value be the previous entry!
    guidata(hObject,handles); %# Note that you don't need to save the handles structure unless
                              %# you have changed a user-defined value like sampledistPrev
                              %# It may still be useful to do it so you always remember
else
   set(handles.sampledist,'String',['',input]);
   %# also update the reset value
   handles.sampledistPrev = input;
   guidata(hObject,handles);
end

Другие советы

Почему вы не храните «предыдущее значение» как «userdata» этого объекта, следующим образом:


function sampledist_Callback(hObject, eventdata, handles)
    input = str2double(get(hObject,'String'));
    if (input < 0 || input > 500)
        errordlg('Sampled Dist. must be > 0 and < 500','Sample Dist - Input Error');
        val=get(hObject,'UserData');
        if isempty(val)
            val='';
        end
        set(hObject,'String',val); %<--- This is where you'd like to set the previous entry value!
        guidata(hObject,handles);
    else
        input=num2str(input);
        set(handles.sampledist,'String',input,'UserData',input);
        guidata(hObject,handles);
    end
end

% YT.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top