I've created a slider in matlab that has a minimum value of -5 and and maximum of plus 5. I want the sliders initial value to be set at 0 (the middle of the slider) and for the current slider value to be put in an edit box underneath the slider. My problem is that I also need to set the focus to the slider so it's immediately operable by keyboard. I've tried using the setfocus function from the Matlab file exchange, but this results in the slider stepping down to -5 when the gui loads up (on account of it simulating a mouse click in the top left corner of the UI object). Trying to reset the value of the slider after the setfocus function call doesn't work either.
Below is some example code that demonstrates the problem (Note, you'll also need the setfocus .m file available from: http://www.mathworks.com/matlabcentral/fileexchange/1898-setfocus)
Code:
function slider_test
% Test script for slider. Need to maximise the figure window in order to
% see the slider.
h.window = figure;
%% Create UI Elements
h.slider = uicontrol ('Parent', h.window, 'Style', 'slider', 'Min', -5, 'Max', 5, ...
'Value', 0, 'Position', [200, 50, 200, 50], 'SliderStep', [0.1, 0.1]);
h.TIvalue = uicontrol('Parent', h.window, 'Style', 'edit', 'String', 0, 'Position', ...
[300, 100, 300, 100], 'FontSize', 16);
%
%% Set callbacks
set(h.slider, 'Callback', @Slider_CallBack);
setfocus(h.slider)
function Slider_CallBack(hObject, event)
%Takes slider value and puts it into the editable text box
SliderValue = get(h.slider,'Value');
set(h.TIvalue,'String', num2str(SliderValue));
set(h.slider,'Value', SliderValue);
end
end
Any other ideas on how to get round this?
Thanks,
Martin
Positionproperty of graphics objects it's safest to also specify the'Units'property. Defaults are not always consistent between users and/or versions of MATLAB. - excaza