Need to position cursor at a specific character in a UIEditField string
9 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Thomas Engel
am 16 Nov. 2023
Beantwortet: Githin George
am 11 Dez. 2023
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,
0 Kommentare
Akzeptierte Antwort
Githin George
am 11 Dez. 2023
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 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Characters and Strings finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!