Search code examples
matlabmatlab-uitable

Resize rowname column width of uitable in MATLAB


I have an uitable in MATLAB with rownames. The column with the rownames is excessively wide and I want to make it "tight" - how do I resize the rownames column of an uitable?


Solution

  • The below code example includes a method to do this. Cheers.

    FontSize = 18;
    fh = figure;
    data =  {1,1,1,1; 2,2,1,1; 3,6,1,1; 4,4,4,1; 6,5,4,1};
    cnames = {'Speed (kph)','Curvature (m)','Banking (deg)','Elevation (m)'};
    rnames = {'Braking','Entry','Mid Corner', 'Mid Throttle', 'Exit'};
    t = uitable('Units','normalized','Position',[0 0 1 
    1],'Data',data,'ColumnName',cnames,'RowName',rnames,'FontSize',FontSize);
    
    hs = '<html><font size="+2">'; %html start
    he = '</font></html>'; %html end
    cnh = cellfun(@(x)[hs x he],cnames,'uni',false); %with html
    rnh = cellfun(@(x)[hs x he],rnames,'uni',false); %with html
    set(t,'ColumnName',cnh,'RowName',rnh) %apply
    
    %get the row header
    jscroll=findjobj(t);
    rowHeaderViewport=jscroll.getComponent(4);
    rowHeader=rowHeaderViewport.getComponent(0);
    height=rowHeader.getSize;
    rowHeader.setSize(80,360)
    
    %resize the row header
    newWidth=150; %100 pixels.
    rowHeaderViewport.setPreferredSize(java.awt.Dimension(newWidth,0));
    height=rowHeader.getHeight;
    rowHeader.setPreferredSize(java.awt.Dimension(newWidth,height));
    rowHeader.setSize(newWidth,height);
    
    figPos = get(fh,'Position');
    tableExtent = get(t,'Extent');
    set(fh,'Position',[figPos(1:2), figPos(3:4).*tableExtent(3:4)]);