Search code examples
stringmatlabuser-interfacelistboxuicontrol

Matlab - Display trailing edge of a long strings in a listbox by hovering the mouse over the string


I have a Matlab listbox on which some strings are very long. I do not want to make listbox too wide just only because of these few long strings. Is there anyway to display trailing edge of these long strings in my listbox by simply hovering the mouse over those strings without using scroll pane?


Solution

  • See Jan's answer using Java objects. Worked great.

    % Prepare the Matlab listbox uicontrol
    hFig = figure;
    listItems =   {'apple','orange','banana','lemon','cherry','pear','melon'};
    hListbox = uicontrol(hFig, 'style','listbox', 'pos',[20,20,60,60],  'string',listItems);
    
    % Get the listbox's underlying Java control
    jScrollPane = findjobj(hListbox);
    
    % We got the scrollpane container - get its actual contained listbox control
    jListbox = jScrollPane.getViewport.getComponent(0);
    
    % Convert to a callback-able reference handle
    jListbox = handle(jListbox, 'CallbackProperties');
    % Set the mouse-movement event callback
    set(jListbox, 'MouseMovedCallback', {@mouseMovedCallback,hListbox});
    
    % Mouse-movement callback
    function mouseMovedCallback(jListbox, jEventData, hListbox)
    % Get the currently-hovered list-item
    mousePos = java.awt.Point(jEventData.getX, jEventData.getY);
    hoverIndex = jListbox.locationToIndex(mousePos) + 1;
    listValues = get(hListbox,'string');
    hoverValue = listValues{hoverIndex};
    
    % Modify the tooltip based on the hovered item
    msgStr = sprintf('<html>item #%d: <b>%s</b></html>', hoverIndex, hoverValue);
    set(hListbox, 'Tooltip',msgStr);
    end  % mouseMovedCallback
    

    https://www.mathworks.com/matlabcentral/answers/436048-display-trailing-edge-of-a-long-strings-of-a-listbox-by-hovering-the-mouse-over-the-string#answer_352806