Table scroll position - Update problem

5 views (last 30 days)
Hello, I have the following problem. I am appending new empty rows to a table in my GUI with this code:
function AddNRows(handles,newRow)
% appends N empty rows to the end of table
%
% handles --> handles structure of GUI
% newRows --> number of new rows
% handles.DataTable is the name of the table
oldData = get(handles.DataTable,'Data'); % get old data from table
nRows = size(oldData,1); % get actual row number
data = cell(nRows+newRow,3); % create new cell with additional rows
data(1:nRows,:) = oldData; % store old data in new cell
set(handles.DataTable,'Data',data) % modify Data field of table
guidata(handles.DataTable,handles)
My original problem was that every time this function is evaluated, the scroll jumps up to the original position, which is really bothering since the new rows are added to the end of the table. The solution I found ( http://undocumentedmatlab.com/blog/customizing-listbox-editbox-scrollbars ) is to use this code:
jScrollpane = findjobj(handles.DataTable); % get the handle of the table
scrollMax = jScrollpane.getVerticalScrollBar.getMaximum; % get the end position of the scroll
AddNRows(handles,1); % appending 1 new row
jScrollpane.getVerticalScrollBar.setValue(scrollMax); % set scroll position to the end
And here is the funny thing! If I run this code in debug mode, step-by-step, my problems are solved, new rows are added and the scroll stays where it should (or actually jumps to the end after the GUI element is updated). But when I run the code normally, without debugging, the scroll jumps back to the zero position, as if setValue(scrollMax) wouldn't be there.
Any idea what is happening?

Accepted Answer

matt dash
matt dash on 17 Dec 2014
Usually when something works in debug mode but not in normal operation, it means you need to add a "drawnow" to your code. In debug mode, there is an implicit "drawnow" that occurs each time you step through the code. Try adding one before the "scrollMax=..." line and see if that fixes it.
  3 Comments
Kristoffer Walker
Kristoffer Walker on 13 Dec 2019
I had the same issue, but this solution did not work for me. 2019b.
Kris
Walter Roberson
Walter Roberson on 13 Dec 2019
Sometimes you need a little pause() to give time for the drawnow to work.

Sign in to comment.

More Answers (0)

Categories

Find more on Programming in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!