MATLAB: How to determine the number of elements that can be displayed at one time in a List Box in MATLAB 7.9 (R2009b)

listboxlistboxlengthMATLABuicontrol

I am building a GUI and I wish to determine the number of items that can fit on the visible portion of the List Box. This GUI will be used on different operating systems which may have different font sizes, screen resolutions, etc. Thus, the number of lines of text displayed in the List Box is not necessarily predictable.
The 'ListBoxTop' property can be used to set or query the index of the top-most item displayed in the listbox. I am looking for something like a 'ListBoxBottom' property to access the index of the last item displayed in the List Box.

Best Answer

There is no direct way to query either the number of items displayed in the List Box or the index of the last item displayed currently displayed.
The following code illustrates one workaround that can be used to determine the number of lines of text that can be viewed at one time in the List Box. Note that this code assumes that the List Box contains more items than can be displayed at one time.
strs = {'one','two','three','four','five','six','seven','eight'};
num_strs = numel(strs); % total number of items to be displayed in the List Box
h = uicontrol('Style','listbox', 'Units','inches', 'Position',[1 1 2 1], ...
'String',strs);
drawnow
% First set the 'ListBoxTop' property to the total number of items in the
% List Box. This has the effect of scrolling to the bottom of the List Box
set(h, 'ListBoxTop',num_strs);
drawnow
% Next query the value of 'ListBoxTop'
top_index = get(h, 'ListBoxTop');
% The difference between the total number of items in the List Box and the
% index of the top item when we have scrolled to the bottom of the list
% gives the number of items that can be displayed at one time
fprintf('%d items can be completely displayed at once\n', num_strs-top_index)
Note that the above example makes use of DRAWNOW a few times due the following bug which prevents the 'ListBoxTop' property from being updated:
<http://www.mathworks.com/support/bugreports/249434>