How to automatically scroll a textbox to end of line?

Hi all,
I'm trying to code a calculator, which has an inactive (non-editable) textbox used for display of the input. Is there a way to automatically scroll the textbox to the end when the input gets longer than the width of the textbox? (If it's impossible in matlab maybe there's some workaround in java?)
Thanks!
Niko

 Accepted Answer

Niko - if you go to the MATLAB File Exchange and download the submission findjobj and save this file somewhere in your MATLAB search path, then you can update your GUI with the following two lines of code that will set the caret to the end of the line in your edit box so that it creates the appearance of automatically scrolling to the end
% assume that the text box that has been updated with the user input is named
% text1
% after text1 has been updated, move the caret to the end of the line
jhText1 = findjobj(handles.text1);
jhText1.setCaretPosition(jhText1.getDocument.getLength);
I tried out the following by creating a simple GUI using GUIDE. (If you created your GUI in a different manner, then you will just have to replace handles.text1 with the handle to your non-editable text box.
The above worked in my version of MATLAB R2014a on OS X 10.8.5.

4 Comments

Hi Geoff,
thanks for the reply, but for some reason it's not working for me. I checked the position of the caret using getCaretPosition() and it seems to be at the right place, but the textbox is not scrolling to the caret position. I'm using MATLAB 2013b on Windows 7; is that making the difference?
Thanks,
Niko
Hi Niko - the problem with using Java, to do something like the above, is that it is unsupported functionality that may work. In this case, it worked for me but not you. (In another case, someone else used Java to change a background colour which worked for him, but not when I tried it.)
You can post the code that you are using to move the caret. But since you have verified with getCaretPosition that the caret seems to be in the correct place, then it sounds like you have the code working...you are just not getting the desired results. Is the HorizontalAlginment property for your text field/widget set to right? (I don't know if this will make a difference or not.)
Niko
Niko on 16 Sep 2014
Edited: Niko on 16 Sep 2014
Hi Geoff,
I just solved the mystery - I put the setCaretPosition() call immediately after I changed the content of the textbox, which actually takes effect after setCaretPosition() is executed since it takes some time to run, and changing the content (from a function rather than manual input) seems to reset caret position to 0. So I added pause(0.01) before setCaretPosition and now it works. Thanks again for your help!
Niko
Great that it worked out!

Sign in to comment.

More Answers (0)

Categories

Asked:

on 13 Sep 2014

Commented:

on 16 Sep 2014

Community Treasure Hunt

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

Start Hunting!