MATLAB Answers

How to compose a formula in a GUI

30 views (last 30 days)
Luc
Luc on 2 May 2011
Hello,
In my GUI a have a list box (lstVariables) with variable names and an edit box (txtEditor) where I want to write a formula. When I click in the list box, I want to add the selected variable in the edit box. The difficulty is that I want to add it on the place where the cursor was.
Example : I have in the edit box the text : "var1 + var2 + var3", I select in the edit box "var2" (so it's highlighted) and than I click in the listbox on var4. The result should be : "var1 + var4 + var3". How can I find which part of the edit box is selected ?
My Example code up to now :
function lstVariables_Callback(hObject, eventdata, handles)
varnames = cellstr(get(hObject,'String'))
varname = varnames{get(hObject,'Value')}
set(handles.txtEditor,'String',varname);
All help is appreciated.
Best regards,
Luc.

  0 Comments

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 2 May 2011
You will have to work at the Java level for this, in order to find out what was highlighted. I recommend that you look at Yair Altman's site, http://undocumentedmatlab.com

  0 Comments

Sign in to comment.

More Answers (1)

Luc
Luc on 2 May 2011
Thank you for the answer, Walter. Based upon Yair Altmans information I composed this code:
function StoreSelectionPositions(hObject, handles)
jEdit = findjobj(hObject);
SelectionStart = get(jEdit, 'SelectionStart');
SelectionEnd = get(jEdit, 'SelectionEnd');
set(handles.lblMessage,'String',[num2str(SelectionStart) ' ' num2str(SelectionEnd)]);
set(hObject,'UserData',[SelectionStart SelectionEnd]);
I call this code in the KeyPressFcn Callback and it works fine when I use the arrow keys to select something. I use the same code in the ButtonDownFcn, but the code is NOT executed when I use the mouse to select part of the text. Any idea how I can fix this ?

  1 Comment

Walter Roberson
Walter Roberson on 2 May 2011
No text would have been selected at ButtonDownFcn time; the selection is made at ButtonUpFcn time.

Sign in to comment.

Sign in to answer this question.