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

6 次查看(过去 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 中查找有关 Labels and Annotations 的更多信息

产品


版本

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by