2017-06-15 35 views
1

我的GUI有兩個編輯框(uicontrol),我想通過左鍵單擊它來更改它們的背景顏色。對於鼠標左鍵單擊,ButtonDownFcn只有在uicontrol Enable屬性設置爲'inactive'或'off'時纔有效,所以我切換屬性以使其工作。uicontrol上的ButtonDownFcn

通過按Tab鍵,我希望我的編輯框將其背景顏色重新初始化爲白色,並更改下一個編輯框的背景顏色。問題是,按下Tab鍵,焦點不會改變,因爲uicontrol啓用屬性是'關閉'或'非活動'。 是否有解決方法?

這是我的代碼到目前爲止。 (EDIT1和EDIT2有相同的代碼)

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 

回答

1

可以使用uicontrols的無證功能並設置適當的行動實現moue焦點時。

這是通過查找底層java對象並設置適當的回調來完成的。

的Java對象是使用"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 
+0

謝謝你發現,它完美的作品。只是一個細節:gainFocus函數(hFig)的第一個參數未被使用,因此可以將其刪除。 – oro777