필터 지우기
필터 지우기

Need to position cursor at a specific character in a UIEditField string

조회 수: 3 (최근 30일)
I'm using a UIEditField in App Designer. I replace certain characters with symbols as the User types using a ValueChanging callback, see code below.
% Value changing function: Entry11, Entry11_2, Entry12, Entry12_2,
% ...and 2 other components
function GroupEntryValueChanging(app, event)
h = gcbo; % get handle of callback function
firstStr = strrep(event.Value,'D',char(176)); % change "d" to degree symbol
lastStr = strrep(firstStr,'A',char(8736)); % change "a" to angle symbol
h.Value = lastStr; % change edit box text
end
This works as desired and replaces the characters. The problem is cursor placement when inserting the special characters "A" or "D" in the middle of a string. The cursor jumps to the end of the string, which is annoying and not User friendly. And I understand the cursor will obviously be located at the end of the new string sent to the editbox.
I could correct this behavior using (1) strfind to know where the character is located in the old string and (2) position the cursor there after sending the new string. Is there any Matlab command or other code to position the cursor within the string? Perhaps this is the wrong approach, Is there an easier way to do this?
Kind regards,

채택된 답변

Githin George
Githin George 2023년 12월 11일
Hello,
My understanding is that you are working on a “uieditfield” graphics object and would like to use the “ValueChangingFcn” callback in a way that the cursor does not re-position itself to the end of the string.
The MATLAB documentation does not provide a way to achieve this behaviour but as a workaround, you can use the following code in your callback to change cursor position towards left or right.
robot = java.awt.Robot;
% to simulate a left arrow key press
robot.keyPress(java.awt.event.KeyEvent.VK_LEFT);
robot.keyRelease(java.awt.event.KeyEvent.VK_LEFT);
% to simulate a left arrow key press
robot.keyPress(java.awt.event.KeyEvent.VK_RIGHT);
robot.keyRelease(java.awt.event.KeyEvent.VK_RIGHT);
You can use the “strfind” function in combination with the above code to manually set cursor location to the position where an edit was made.
An even better solution would be to use the “ValueChangedFcn” Callback as it would replace the whole string on pressing the ‘enter’ key.
I hope this helps.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

제품


릴리스

R2023b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by