oro777
oro777

Reputation: 1110

ButtonDownFcn on uicontrol

My GUI has two edit boxes (uicontrol) and I would like to change their background color by left-clicking on it. For left-mouse click, the ButtonDownFcn works only if the uicontrol Enable property is set to 'inactive' or 'off', so I switch the property to make it work.

By pressing the tab key, I would like my edit box to reinitialize their background color to white and change the background color of the next edit box. The problem is that pressing the tab key, the focus won't change since the uicontrol Enable property are 'off' or 'inactive'. Is there a work-around ?

Here is my code so far. (edit1 and edit2 have the same code)

function edit1_ButtonDownFcn(hObject, eventdata, handles)
set(hObject, 'Enable', 'on', 'BackgroundColor', [0.5,1,0.7]) % change enable and background color properties
uicontrol(hObject) % focus on the current object

function edit1_Callback(hObject, eventdata, handles)
set(hObject, 'Enable', 'inactive', 'BackgroundColor', [1 1 1]) % reinitialize the edit box

Upvotes: 1

Views: 333

Answers (1)

matlabgui
matlabgui

Reputation: 5672

You can use an undocumented feature of the uicontrols to set appropriate action when the moue focus is achieved.

This is done by finding the underlying java object and setting the appropriate callback.

The java object is found using "findjobj" function which you can download from the Mathworks FEX

function test
  %% Create the figure and uicontols
  hFig = figure;
  uic(1) = uicontrol ( 'style', 'edit', 'position', [100 300 200 50], 'parent', hFig );
  uic(2) = uicontrol ( 'style', 'edit', 'position', [100 200 200 50], 'parent', hFig );
  % for each of the uicontrols find the java object and set the FocusGainedCallback
  for ii=1:2
    jObj = findjobj ( uic(ii) );
    set(jObj,'FocusGainedCallback', @(a,b)gainFocus( hFig, uic, ii ));
  end
  % set the defaults.
  gainFocus( hFig, uic, 1 );
end
function gainFocus( hFig, uic, uicIndex )
  switch uicIndex
    case 1
      index = [1 2];
    case 2
      index = [2 1];
  end
  uic(index(1)).BackgroundColor = [1  1. 1];
  uic(index(2)).BackgroundColor = [0.5 1. 0.7];
end

Upvotes: 1

Related Questions