Undocumented Matlab
  • SERVICES
    • Consulting
    • Development
    • Training
    • Gallery
    • Testimonials
  • PRODUCTS
    • IQML: IQFeed-Matlab connector
    • IB-Matlab: InteractiveBrokers-Matlab connector
    • EODML: EODHistoricalData-Matlab connector
    • Webinars
  • BOOKS
    • Secrets of MATLAB-Java Programming
    • Accelerating MATLAB Performance
    • MATLAB Succinctly
  • ARTICLES
  • ABOUT
    • Policies
  • CONTACT
  • SERVICES
    • Consulting
    • Development
    • Training
    • Gallery
    • Testimonials
  • PRODUCTS
    • IQML: IQFeed-Matlab connector
    • IB-Matlab: InteractiveBrokers-Matlab connector
    • EODML: EODHistoricalData-Matlab connector
    • Webinars
  • BOOKS
    • Secrets of MATLAB-Java Programming
    • Accelerating MATLAB Performance
    • MATLAB Succinctly
  • ARTICLES
  • ABOUT
    • Policies
  • CONTACT

Uitable sorting

July 26, 2011 45 Comments

uitable is probably the most complex basic GUI controls available in Matlab. It displays data in a table within a figure, with settable properties as with any other Matlab Handle-Graphics (HG) control. After many years in which the uitable was available but semi-documented and not officially supported in Matlab, it finally became fully documented and supported in R2008a (aka Matlab 7.6). At that time its internal implementation has changed from a MathWorks-developed Java table to a JIDE-based Java table (another JIDE-derived table was described here last year). Since R2008a, both versions of uitable are available – the old version is available by adding the ‘v0’ input arg.
Matlab’s uitable exposes only a very limited subset of functionalities and properties to the user. Numerous other functionalities are available by accessing the underlying Java table and hidden Matlab properties. Today I will describe a very common need in GUI tables, that for some unknown reason is missing in Matlab’s uitable: Sorting table data columns.
Last week I explained how we can modify table headers of an ActiveX table control to display sorting icons. In that case, sorting was built-in the control, and the question was just how to display the sorting arrow icon. Unfortunately, Matlab’s uitable does not have sorting built-in, although it’s quite easy to add it, as I shall now show.

Old uitable sorting

The old uitable is the default control used until R2007b, or that can be selected with the ‘v0’ input arg since R2008a. It was based on an internal MathWorks extension of the standard Java Swing JTable – a class called com.mathworks.widgets.spreadsheet.SpreadsheetTable.
Users will normally try to sort columns by clicking the header. This has been a deficiency of JTable for ages. To solve this for the old (pre-R2008a) uitable, download one of several available JTable sorter classes, or my TableSorter class (available here). Add the TableSorter.jar file to your static java classpath (via edit('classpath.txt')) or your dynamic classpath (javaaddpath('TableSorter.jar')).

% Display the uitable and get its underlying Java object handle
[mtable,hcontainer] = uitable('v0', gcf, magic(3), {'A', 'B', 'C'});   % discard the 'v0' in R2007b and earlier
jtable = mtable.getTable;   % or: get(mtable,'table');
% We want to use sorter, not data model...
% Unfortunately, UitablePeer expects DefaultTableModel not TableSorter so we need a modified UitablePeer class
% But UitablePeer is a Matlab class, so use a modified TableSorter & attach it to the Model
if ~isempty(which('TableSorter'))
   % Add TableSorter as TableModel listener
   sorter = TableSorter(jtable.getModel());
   jtable.setModel(sorter);
   sorter.setTableHeader(jtable.getTableHeader());
   % Set the header tooltip (with sorting instructions)
   jtable.getTableHeader.setToolTipText('<html>&nbsp;<b>Click</b> to sort up; <b>Shift-click</b> to sort down<br />&nbsp;...</html>');
else
   % Set the header tooltip (no sorting instructions...)
   jtable.getTableHeader.setToolTipText('<html>&nbsp;<b>Click</b> to select entire column<br />&nbsp;<b>Ctrl-click</b> (or <b>Shift-click</b>) to select multiple columns&nbsp;</html>');
end

% Display the uitable and get its underlying Java object handle [mtable,hcontainer] = uitable('v0', gcf, magic(3), {'A', 'B', 'C'}); % discard the 'v0' in R2007b and earlier jtable = mtable.getTable; % or: get(mtable,'table'); % We want to use sorter, not data model... % Unfortunately, UitablePeer expects DefaultTableModel not TableSorter so we need a modified UitablePeer class % But UitablePeer is a Matlab class, so use a modified TableSorter & attach it to the Model if ~isempty(which('TableSorter')) % Add TableSorter as TableModel listener sorter = TableSorter(jtable.getModel()); jtable.setModel(sorter); sorter.setTableHeader(jtable.getTableHeader()); % Set the header tooltip (with sorting instructions) jtable.getTableHeader.setToolTipText('<html>&nbsp;<b>Click</b> to sort up; <b>Shift-click</b> to sort down<br />&nbsp;...</html>'); else % Set the header tooltip (no sorting instructions...) jtable.getTableHeader.setToolTipText('<html>&nbsp;<b>Click</b> to select entire column<br />&nbsp;<b>Ctrl-click</b> (or <b>Shift-click</b>) to select multiple columns&nbsp;</html>'); end

Sorted uitable - old version
Sorted uitable - old version

New uitable sorting

The new uitable is based on JIDE’s com.jidesoft.grid.SortableTable and so has built-in sorting support – all you need to do is to turn it on. First get the underlying Java object using my FindJObj utility:

% Display the uitable and get its underlying Java object handle
mtable = uitable(gcf, 'Data',magic(3), 'ColumnName',{'A', 'B', 'C'});
jscrollpane = findjobj(mtable);
jtable = jscrollpane.getViewport.getView;
% Now turn the JIDE sorting on
jtable.setSortable(true);		% or: set(jtable,'Sortable','on');
jtable.setAutoResort(true);
jtable.setMultiColumnSortable(true);
jtable.setPreserveSelectionsAfterSorting(true);

% Display the uitable and get its underlying Java object handle mtable = uitable(gcf, 'Data',magic(3), 'ColumnName',{'A', 'B', 'C'}); jscrollpane = findjobj(mtable); jtable = jscrollpane.getViewport.getView; % Now turn the JIDE sorting on jtable.setSortable(true); % or: set(jtable,'Sortable','on'); jtable.setAutoResort(true); jtable.setMultiColumnSortable(true); jtable.setPreserveSelectionsAfterSorting(true);

Note: the Matlab mtable handle has a hidden Sortable property, but it has no effect – use the Java property mentioned above instead. I assume that the hidden Sortable property was meant to implement the sorting behavior in R2008a, but MathWorks never got around to actually implement it, and so it remains this way to this day.

A more detailed report

I have prepared a 45-page PDF report about using and customizing Matlab’s uitable, which greatly expands on the above. This report is available for $25 here (please allow up to 48 hours for email delivery). The report includes the following (more details here):

  • comparison of the old vs. the new uitable implementations
  • description of the uitable properties and callbacks
  • alternatives to uitable using a variety of technologies
  • updating a specific cell’s value
  • setting background and foreground colors for a cell or column
  • using dedicated cell renderer and editor components
  • HTML processing
  • setting dynamic cell-specific tooltip
  • setting dynamic cell-specific drop-down selection options
  • using a color-selection drop-down for cells
  • customizing scrollbars
  • customizing column widths and resizing
  • customizing selection behavior
  • data sorting (expansion of today’s article)
  • data filtering (similar to Excel’s data filtering control)
  • merging table cells
  • programmatically adding/removing rows
  • numerous links to online resources
  • overview of the JIDE grids package, which contains numerous extremely useful GUI controls and components

Related posts:

  1. Uitable customization report – Matlab's uitable can be customized in many different ways. A detailed report explains how. ...
  2. Uitable cell colors – A few Java-based customizations can transform a plain-looking data table into a lively colored one. ...
  3. Multi-line uitable column headers – Matlab uitables can present long column headers in multiple lines, for improved readability. ...
  4. Matlab and the Event Dispatch Thread (EDT) – The Java Swing Event Dispatch Thread (EDT) is very important for Matlab GUI timings. This article explains the potential pitfalls and their avoidance using undocumented Matlab functionality....
  5. Tab panels – uitab and relatives – This article describes several undocumented Matlab functions that support tab-panels...
  6. treeTable – A description of a sortable, groupable tree-table control that can be used in Matlab is provided. ...
GUI Hidden property HTML Internal component Java JIDE Semi-documented function uitable uitools Undocumented feature
Print Print
« Previous
Next »
45 Responses
  1. Arda July 27, 2011 at 06:22 Reply

    Hello Yair,
    Without knowing your post, i have posted about this subject at Matlab Newsreader. 🙂
    https://www.mathworks.com/matlabcentral/newsreader/view_thread/310934/

    However i still couldnt find a way to get the selected cell information. After sorting the data, I try to get the selected cell position (relative to table) with “eventData.Indices” and using the getSortedRowAt with column indice, it is supposed to give me the position of selected cell relative to the original data. My code is;
    jtable.getSortedRowAt(eventData.Indices(1))
    The results are incorrect most of the time unfortunately. Do i make any mistake?

    • Yair Altman July 27, 2011 at 08:14 Reply

      @Arda – this is answered in the report…

      • Arda July 27, 2011 at 09:37

        Yair thanks for the guide, I have figured it out.

  2. Aurélien July 27, 2011 at 07:59 Reply

    WOW ! thanks Yair: I was rightly looking for this week an easy way to achieve this task : sorting an uitable.
    You gave me the answer. Thanks again!

  3. Yun August 4, 2011 at 22:14 Reply

    Maybe I’m not doing this right, but the new JIDE uitable sort is sorting the values as string only. Even though it is displayed as numbers, right justified, it sorts 3,10,30 as 10,3,30.

    • Yun August 12, 2011 at 09:42 Reply

      Okay it looks like the the new uitable uses default table model, getColumnClass always returns java.lang.Object, so sorting would not be correct for numbers fields even if column format is set to numeric. If there is no reasonably easy way to change this, it significantly reduces the usefulness the new uitable sorting capability.

    • Yair Altman August 14, 2011 at 19:10 Reply

      A workaround for sorting numbers in uitable is detailed in the report…

    • Yun August 16, 2011 at 21:01 Reply

      I’m feeling dumb. I read through the report, and can’t seem to find any reference to the workaround for dealing with numbers with the new uitable.

    • Yair Altman August 16, 2011 at 23:32 Reply

      @Yun – I believe that you read the blog post, not the report. The report is a 35-page document that is available for a small fee here.

  4. Drew October 10, 2011 at 13:16 Reply

    When I have a large number of rows in the uitable, sorting doesn’t function correctly. Do you run into this problem? If yes, is there a way to fix it?
    System info: Windows 7 64-bit, Matlab r2011a 64-bit

    % integers for display
    data = round(9*rand(1000,3));
     
    % Display the uitable and get its underlying Java object handle
    mtable = uitable(gcf,'Data',data,'units','normalized','position',[0 0 1 1]);
    jscrollpane = findjobj(mtable);
    jtable = jscrollpane.getViewport.getView;
     
    % turn JIDE sorting on
    jtable.setSortable(true);
    jtable.setAutoResort(true);
    jtable.setMultiColumnSortable(false);
    jtable.setPreserveSelectionsAfterSorting(true);

    % integers for display data = round(9*rand(1000,3)); % Display the uitable and get its underlying Java object handle mtable = uitable(gcf,'Data',data,'units','normalized','position',[0 0 1 1]); jscrollpane = findjobj(mtable); jtable = jscrollpane.getViewport.getView; % turn JIDE sorting on jtable.setSortable(true); jtable.setAutoResort(true); jtable.setMultiColumnSortable(false); jtable.setPreserveSelectionsAfterSorting(true);

    • Yair Altman October 11, 2011 at 01:58 Reply

      @Drew – strange indeed. Looks like a JIDE bug to me… Maybe this is the reason for sorting not being exposed in Matlab.

    • Marie-Helene Lavoie August 8, 2013 at 12:29 Reply

      I have the same problem with large number of rows. Moreover, the sorting doesn’t comply with the locale (I’m french canadian). In the following example, ‘Éric’ and ‘Eric’ should be sorted after ‘Aude’ and before ‘Marc’.

      data = {'Lavoie3','Éric';'Lavoie','Marc';'Lavoie','Aude';'Lavoie2','Éric';'Lavoie2','Eric';'Lavoie','Eric'};
      % figure and table
      f=figure;
      p=get(f,'pos');
      th=uitable(f,'pos',[0 0 p(3:4)],'ColumnName',{'Nom','Prénom'},'data',data);
      jPane = findjobj(th,'-nomenu','property',{'Width',p(3)}); %pane
      jTable = jPane.getViewport.getView; %table
      % sorting
      jTable.setSortable(true);
      jTable.setAutoResort(true);
      jTable.setPreserveSelectionsAfterSorting(true);
      jTable.setMultiColumnSortable(true);

      data = {'Lavoie3','Éric';'Lavoie','Marc';'Lavoie','Aude';'Lavoie2','Éric';'Lavoie2','Eric';'Lavoie','Eric'}; % figure and table f=figure; p=get(f,'pos'); th=uitable(f,'pos',[0 0 p(3:4)],'ColumnName',{'Nom','Prénom'},'data',data); jPane = findjobj(th,'-nomenu','property',{'Width',p(3)}); %pane jTable = jPane.getViewport.getView; %table % sorting jTable.setSortable(true); jTable.setAutoResort(true); jTable.setPreserveSelectionsAfterSorting(true); jTable.setMultiColumnSortable(true);

      Using jTable.setAutoCreateRowSorter(true) comply with the locale but do not allow for multi column sorting…

  5. Nath October 15, 2011 at 05:44 Reply

    As we can change the column-format property to checkbox, popupmenu options in the uitable, I need help for changing the column-format property to radio-button.

    Help me regarding this issue……….

  6. Uitable cell colors | Undocumented Matlab October 27, 2011 at 03:50 Reply

    […] are still quite a few other customizations needed here: enable sorting; remove the border outline; set a white background; set row (rather than cell) selection and […]

  7. Jayveer December 10, 2011 at 00:11 Reply

    Hi

    For some strange reason, the ‘new uitable sorting’ isn’t working on windows 7 64 bit. It works fine on lion.

    I get the following error:

    No appropriate method, property, or field getViewport for class
    handle.handle.

    Error in MPMSimPre>MPMSimPre_OutputFcn (line 349)
    jtable = jscrollpane.getViewport.getView;

    Error in gui_mainfcn (line 265)
    feval(gui_State.gui_OutputFcn, gui_hFigure, [], gui_Handles);

    Error in MPMSimPre (line 280)
    gui_mainfcn(gui_State, varargin{:});

    Please advise.

    Matlab Version: R2011b Win 64bit

    • Yair Altman December 13, 2011 at 15:01 Reply

      @Javveer – this is because findjobj doesn’t find the table reference for some unknown reason. Try playing around with different parameters, maybe move the table a bit in the figure, maybe download the latest version of findjobj. If all this still doesn’t work, you can either debug findjobj step-by-step with the debugger, or use a different sorting mechanism, or implement a pure-Java table. As a last resort, you can always use my consulting skills…

    • Jveer January 3, 2012 at 23:32 Reply

      @Yair

      Thank you for the suggestions. Unfortunately none of the simple solutions suggested worked. On snow leopard, placing the sorting code below the one that updates the table seems to do the trick. The only OS the code works flawlessly from within OutputFcn is Lion.

  8. Sebas December 16, 2013 at 07:37 Reply

    Ciao Yair,

    first, thanks you for your fantastic website!

    I’m using the JIDE-based Java table, your example works perfectly. There is only one problem when I try to use a specific filter: “condition”->”is in”->”value(s)”. It opens a checkbox list but when I click on one checkbox, I get a very long error in my command window starting with:

    Exception occurred during event dispatching:
    java.lang.NullPointerException
    	at com.jidesoft.combobox.ExComboBox.validateValueForNonEditable(Unknown Source)
    	at com.jidesoft.combobox.MultiSelectListExComboBox.validateValueForNonEditable(Unknown Source)
    	at com.jidesoft.combobox.ExComboBox.setSelectedItem(Unknown Source)
    	at com.jidesoft.combobox.MultiSelectListExComboBox.setSelectedItem(Unknown Source)
    ...
    

    and of course the filtering does not work. This is a shame because this kind of filter is what I was looking for!

    Have you got any idea about how to fix this problem?

    Thank you very much for your help.

    Seb

    • Yair Altman December 16, 2013 at 09:42 Reply

      @Sebas – I’m not sure exactly how you got there but in any case it looks like something that requires some investigation. If you’d like me to check this out for you, contact me by email for a short consulting proposal.

  9. Luc Le Blanc March 11, 2014 at 12:25 Reply

    Is it me or doubles are not properly sorted by the new uitable? In decreasing order (arrow pointing down), I have:

    750.1248
    671.5008
    2.1361e+03

    I double-checked and the data is doubles (…), not strings. Integers don’t exhibit this problem.

    • Yair Altman March 11, 2014 at 13:10 Reply

      @Luc – this is correct. Doubles are sorted lexically (’12’ < ‘6’), not numerically (12 > 6). My uitable report has some workarounds.

  10. Ange Kouemo August 27, 2015 at 07:21 Reply

    Hi Yair,

    I am using Matlab 2014b and created a Uitable that I want to display in a Jpanel. I tried to get the underlying Java object handle of the uitable using the functions you suggested above:

    [mtable,hcontainer] = uitable('v0', gcf, magic(3), {'A', 'B', 'C'});   % discard the 'v0' in R2007b and earlier
    jtable = mtable.getTable;   % or: get(mtable,'table');

    [mtable,hcontainer] = uitable('v0', gcf, magic(3), {'A', 'B', 'C'}); % discard the 'v0' in R2007b and earlier jtable = mtable.getTable; % or: get(mtable,'table');

    Unfortunately I get the following error:

    No appropriate method, property, or field getTable for class matlab.ui.control.Table.

    No appropriate method, property, or field getTable for class matlab.ui.control.Table.

    Can you please help to come up with this problem? Thanks!

    Regards,
    Ange Laure

    • Yair Altman September 18, 2015 at 04:44 Reply

      @Ange – mtable.getTable only works on the old (pre-R2008a) uitable; with the new (R2008a onward) uitable you need to use the findjobj utility to get the underlying Java object.

      You can read all about it in my uitable customization report.

  11. Amit March 13, 2016 at 15:10 Reply

    Hi Yair,

    Like you mention that the workaround to sort numerically (rather than lexically) is mentioned in your uitable report, is it mentioned in your ‘Undocumented secrets of MATLAB’ book? Or do I need to get that uitable report too specifically for this?

    Many thanks for all your articles. You had been a life saver so many times.

    Cheers…

    • Yair Altman March 13, 2016 at 21:20 Reply

      @Amit – unfortunately I only refer to this issue in my report, not the book. My Matlab-Java book was published 4.5 years ago and in the meantime I expanded the coverage of uitable in my uitable customization report, so it now contains more contents than the book, including this specific feature. On the other hand, the book includes a lot of other content that is not related to uitable. Also, the report is in full-color PDF format, whereas the book is not. So while there is overlap between the book and the report, they are different in important ways, and complement each other.

    • Amit March 13, 2016 at 21:54 Reply

      Are you working on new editions of both of your books? I would love get updated editions. I am going for your uitable report meantime. Thanks for your help.

  12. Praneeth April 18, 2016 at 17:01 Reply

    Hi Yair,

    I tried using getSelectionModel and Valuechangedcallback but with a single mouse click function is getting executed multiple times with same data and finally giving output and an error saying “exception in thread AWT=EventQueue-0”

    can you please help with this

    • Yair Altman April 18, 2016 at 17:47 Reply

      @Praneeth – you need to handle this programmatically, within your Matlab callback function. For example:

      function myCallbackFunc(hObject, eventData)
         if eventData.getValueIsAdjusting,  return,  end  % immediate bail-out for intermediate events
         ...
      end

      function myCallbackFunc(hObject, eventData) if eventData.getValueIsAdjusting, return, end % immediate bail-out for intermediate events ... end

      Also look at the various mechanism to avoid callback reentrancy here: https://undocumentedmatlab.com/blog/controlling-callback-re-entrancy

    • Praneeth April 18, 2016 at 18:01 Reply

      @Yair – I tried it always value in Valueisadjusting is 0 but still its running in a loop and finally throwing the error “exception in thread AWT=EventQueue-0”.

      Also can you tell me in which page did u mention about sorting numerically with JIDE. i read through your undocumented matlab book but didint find

      • Yair Altman April 19, 2016 at 00:55

        @Praneeth – You did not listen to what I told you: you need to prevent callback reentrancy yourself, in your callback function. Multiple ways to do this are discussed in the webpage that I linked in my previous answer.

        As for numeric sorting, I did not discuss this issue in my book. You basically need to create a custom data model Java class that handles this (or contract me to do it for you).

    • Praneeth April 18, 2016 at 18:04 Reply

      To make it more clear its running multiple times on a single cell value

    • Praneeth April 19, 2016 at 13:51 Reply

      @Yair. Thanks a lot for the reply.

      Callback reentrancy is now controlled but still i am getting the java exception “exception in thread AWT=EventQueue-0”

      Anyway to avoid this?

  13. Shi February 10, 2017 at 11:07 Reply

    Hi,Yair
    I hava a question.when I use jtable.setModel(javax.swing.table.DefaultTableModel(Data,headers)to updata the data in old matlab uitable;I find I cannot use data = cell(mtable.getData)to get the editored data I find use jtable.getModel().getDataVector() can get the data in java.util.Vector .But how I let the the java.util.Vector Data tranfer a cell-style data I try use cell(jtable.getModel().getDataVector()),but the result is [ 1000 java.util.Vector];
    Thanks

    • Yair Altman February 10, 2017 at 12:27 Reply

      data = cell(mtable.getData) should be used but you might need to pause(0.01) to let the data updates propagate from the jtable model to the mtable object.

    • shi February 16, 2017 at 03:38 Reply

      THanks ,it really worked when I didn’t use ColoredFieldCellRenderer.
      it may be the question I use the ColoredFieldCellRenderer to Rendering the cell ,and it shows this Exception :
      Exception in thread “AWT-EventQueue-0” java.lang.NullPointerException
      at ColoredFieldCellRenderer.getTableCellRendererComponent(ColoredFieldCellRenderer.java:101)
      at javax.swing.JTable.prepareRenderer(Unknown Source)
      at javax.swing.JTable.getToolTipText(Unknown Source)
      at javax.swing.ToolTipManager$insideTimerAction.actionPerformed(Unknown Source)
      at javax.swing.Timer.fireActionPerformed(Unknown Source)
      at javax.swing.Timer$DoPostEvent.run(Unknown Source)
      at java.awt.event.InvocationEvent.dispatch(Unknown Source)
      at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
      at java.awt.EventQueue.access$200(Unknown Source)
      at java.awt.EventQueue$3.run(Unknown Source)
      at java.awt.EventQueue$3.run(Unknown Source)
      at java.security.AccessController.doPrivileged(Native Method)
      at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
      at java.awt.EventQueue.dispatchEvent(Unknown Source)
      at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
      at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
      at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
      at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
      at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
      at java.awt.EventDispatchThread.run(Unknown Source)
      I find the jtable.getModel().getDataVector() can shows correct data in jtable.getModel().getDataVector(),while it cannot propagate from the jtable model to the mtable object。

      • Yair Altman May 10, 2017 at 11:24

        @shi – this is an unhandled case in the ColoredFieldCellRenderer code. You have the source code for this class – it is quite simple and you can modify it in a which that will handle sorted data rows.

  14. Jack May 10, 2017 at 04:04 Reply

    Hi Yair

    How can I make the table.Data to be update after i’m sorting a table as like as you described above?
    Because I noticed that after i’m sorting a table the table.Data remains the same as before i sorted the table and actually disconnect what the table showing to the user.

    TNX

    Jack

    • Yair Altman May 10, 2017 at 11:19 Reply

      @Jack – sorting only affects the way that the table-model data is displayed, it does not affect the data itself. You can get the model-to-view mapping using this:

      displayedRowIndex = jtable.getSortedRowAt(modelRowIndex-1) + 1;

      displayedRowIndex = jtable.getSortedRowAt(modelRowIndex-1) + 1;

      Note that java indices start at 0 (not 1 as in Matlab), hence the need for the -1 and +1 in the code snippet above.
      When the table is not sorted, displayedRowIndex will be the same as modelRowIndex; when sorted it will return a different index.

      • Jack May 10, 2017 at 13:26

        Hi Yair

        Thank you very much for your answer.
        Can you explain me please what is the meaning of the index that getSortedRowAt is returning? I noticed it is’nt the row index before the table sorted.

        Thanks,
        Jack

      • Yair Altman May 10, 2017 at 14:18

        jtable.getSortedRowAt(rowIndex) returns the display row index for a specified data model row;
        jtable.getActualRowAt(rowIndex) returns the data model row index for a specified display row.

    • didi May 13, 2017 at 19:55 Reply

      Thank! It’s helped me a lot!

  15. Meade Spratley September 22, 2017 at 01:17 Reply

    Hi Yair,

    I think I have a new problem, maybe you haven’t seen!

    I’m using a uitable to make an interactive name builder. Basically, I’m creating a table with dynamic column names. The user can then change the order to make a new permutation.

    The problem is I can’t figure out a callback that will fire when the columns are rearranged!

    Do you have any thoughts? Ever seen anything similar?

    Again, many thanks for a great blog.
    Best,
    Meade

    function legendFromHeaderGUI_ex()
     
    GUI = figure('Position',[-10000 0 100 100],'Name','Build Legend Name',...
        'CloseRequestFcn','delete(gcf)',...
        'UserData',0,...   
        'Resize','on',...
        'MenuBar', 'none',...
        'ToolBar', 'none',...
        'NumberTitle', 'off',...
        'Visible','on');
     
    RowName = {'FileName',...
        'Field1',...
        'Field2',...
        '...',...
        'FieldN'}';
     
    % Normal Table
    columnformat = {'logical','char'};
    t_data = repmat({false(1,1)},[length(RowName),1]);
     
    t = uitable('Parent',GUI,...
        'Data',[t_data, RowName],...
        'ColumnName',{},...                
        'RowName',{},...
        'ColumnWidth', {40,300},...
        'ColumnFormat', columnformat,...
        'ColumnEditable', [true,false],...
        'FontSize',9,...
        'Tag','t1');
     
    % Update figure size to close-fit the Header table
    t.Position(3) = t.Extent(3);
    t.Position(4) = t.Extent(4);
     
    GUI.Position(3) = t.Extent(3)+400;
    GUI.Position(4) = t.Extent(4)+200;
     
    t.Position(1) = 10;
    t.Position(2) = 150;
     
    %%% Dynamic Table
    t2 = uitable('Parent',GUI,...
        'Data',{},...
        'ColumnName',{},...                
        'RowName',{},...
        'ColumnWidth', {125},...
        'ColumnFormat', {'char'},...
        'ColumnEditable', false,...
        'RearrangeableColumns','on',...
        'FontSize',7,...    'CellEditCallback',@updateLegend2
        'Tag','t2');
     
    t2.Position(3) = t2.Extent(3);
    t2.Position(4) = t2.Extent(4);
     
    %% JAVA for UITABLES
    t2_jscrollpane = findjobj(t2,'-nomenu');  
    t2_jtable = t2_jscrollpane.getViewport.getView;
     
    t.CellEditCallback = {@t1_callback,t2_jtable};
     
    % vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
    %%% t2_jtableh = handle(t2_jtable,'CallbackProperties')         % I'm just lost
    %%% t2.#??CALLBACKHERE# = {@t2_Callback,ht_jtable};
    % ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
     
    com.mathworks.mwswing.MJUtilities.initJIDE;
    com.jidesoft.grid.TableUtils.autoResizeAllColumns(t2_jtable);
     
    gd.Handles = guihandles(GUI);
    guidata(GUI,gd);
     
    movegui(GUI,'center');
     
        function t1_callback(hObj,~,~)
            h = guidata(hObj);
            headers = hObj.Data(:,2);
            flags   = [hObj.Data{:,1}]';
            h.Handles.t2.ColumnName = headers(flags);
            h.Handles.t2.Position(3) = h.Handles.t2.Extent(3);
            h.Handles.t2.Position(4) = h.Handles.t2.Extent(4);       
        end
     
        function t2_Callback(hObj,evt,t2_jh)
            % HOW CAN I FIRE YOU!!!?!?!???
        end
    end

    function legendFromHeaderGUI_ex() GUI = figure('Position',[-10000 0 100 100],'Name','Build Legend Name',... 'CloseRequestFcn','delete(gcf)',... 'UserData',0,... 'Resize','on',... 'MenuBar', 'none',... 'ToolBar', 'none',... 'NumberTitle', 'off',... 'Visible','on'); RowName = {'FileName',... 'Field1',... 'Field2',... '...',... 'FieldN'}'; % Normal Table columnformat = {'logical','char'}; t_data = repmat({false(1,1)},[length(RowName),1]); t = uitable('Parent',GUI,... 'Data',[t_data, RowName],... 'ColumnName',{},... 'RowName',{},... 'ColumnWidth', {40,300},... 'ColumnFormat', columnformat,... 'ColumnEditable', [true,false],... 'FontSize',9,... 'Tag','t1'); % Update figure size to close-fit the Header table t.Position(3) = t.Extent(3); t.Position(4) = t.Extent(4); GUI.Position(3) = t.Extent(3)+400; GUI.Position(4) = t.Extent(4)+200; t.Position(1) = 10; t.Position(2) = 150; %%% Dynamic Table t2 = uitable('Parent',GUI,... 'Data',{},... 'ColumnName',{},... 'RowName',{},... 'ColumnWidth', {125},... 'ColumnFormat', {'char'},... 'ColumnEditable', false,... 'RearrangeableColumns','on',... 'FontSize',7,... 'CellEditCallback',@updateLegend2 'Tag','t2'); t2.Position(3) = t2.Extent(3); t2.Position(4) = t2.Extent(4); %% JAVA for UITABLES t2_jscrollpane = findjobj(t2,'-nomenu'); t2_jtable = t2_jscrollpane.getViewport.getView; t.CellEditCallback = {@t1_callback,t2_jtable}; % vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv %%% t2_jtableh = handle(t2_jtable,'CallbackProperties') % I'm just lost %%% t2.#??CALLBACKHERE# = {@t2_Callback,ht_jtable}; % ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ com.mathworks.mwswing.MJUtilities.initJIDE; com.jidesoft.grid.TableUtils.autoResizeAllColumns(t2_jtable); gd.Handles = guihandles(GUI); guidata(GUI,gd); movegui(GUI,'center'); function t1_callback(hObj,~,~) h = guidata(hObj); headers = hObj.Data(:,2); flags = [hObj.Data{:,1}]'; h.Handles.t2.ColumnName = headers(flags); h.Handles.t2.Position(3) = h.Handles.t2.Extent(3); h.Handles.t2.Position(4) = h.Handles.t2.Extent(4); end function t2_Callback(hObj,evt,t2_jh) % HOW CAN I FIRE YOU!!!?!?!??? end end

    • Yair Altman September 24, 2017 at 10:33 Reply

      @Meade – I do not have an immediate answer, but it’s quite possible that a solution can be found. If you’d like me to investigate this (for a consulting fee) then email me.

  16. Dan August 14, 2018 at 00:46 Reply

    Thank you so much. This works well for UITables embedded in a traditional figure but I’m having issues getting findjobj to work when the UITable is embedded in a UIFigure, it just returns an empty array. (I have an application build in App Designer.) Is there another way to get the Java handle to the UITable when it’s in a UIFigure?

    Thanks,
    Dan

    • Yair Altman August 14, 2018 at 04:04 Reply

      @Dan – uifigures are based on HTML and JavaScript, they are basically nothing more than a webpage displayed within a browser window. In comparison, legacy figures are based on Java desktop windows. So any customization that works on the Java-based figures and relies on Java (including uitable customizations) will never work in uifigures, and you cannot get the Java handle of uifigure components because they’re not based on Java.

      For details on uifigure customizations, refer to the list of posts that have the uifigure tag.

Leave a Reply
HTML tags such as <b> or <i> are accepted.
Wrap code fragments inside <pre lang="matlab"> tags, like this:
<pre lang="matlab">
a = magic(3);
disp(sum(a))
</pre>
I reserve the right to edit/delete comments (read the site policies).
Not all comments will be answered. You can always email me (altmany at gmail) for private consulting.

Click here to cancel reply.

Useful links
  •  Email Yair Altman
  •  Subscribe to new posts (feed)
  •  Subscribe to new posts (reader)
  •  Subscribe to comments (feed)
 
Accelerating MATLAB Performance book
Recent Posts

Speeding-up builtin Matlab functions – part 3

Improving graphics interactivity

Interesting Matlab puzzle – analysis

Interesting Matlab puzzle

Undocumented plot marker types

Matlab toolstrip – part 9 (popup figures)

Matlab toolstrip – part 8 (galleries)

Matlab toolstrip – part 7 (selection controls)

Matlab toolstrip – part 6 (complex controls)

Matlab toolstrip – part 5 (icons)

Matlab toolstrip – part 4 (control customization)

Reverting axes controls in figure toolbar

Matlab toolstrip – part 3 (basic customization)

Matlab toolstrip – part 2 (ToolGroup App)

Matlab toolstrip – part 1

Categories
  • Desktop (45)
  • Figure window (59)
  • Guest bloggers (65)
  • GUI (165)
  • Handle graphics (84)
  • Hidden property (42)
  • Icons (15)
  • Java (174)
  • Listeners (22)
  • Memory (16)
  • Mex (13)
  • Presumed future risk (394)
    • High risk of breaking in future versions (100)
    • Low risk of breaking in future versions (160)
    • Medium risk of breaking in future versions (136)
  • Public presentation (6)
  • Semi-documented feature (10)
  • Semi-documented function (35)
  • Stock Matlab function (140)
  • Toolbox (10)
  • UI controls (52)
  • Uncategorized (13)
  • Undocumented feature (217)
  • Undocumented function (37)
Tags
ActiveX (6) AppDesigner (9) Callbacks (31) Compiler (10) Desktop (38) Donn Shull (10) Editor (8) Figure (19) FindJObj (27) GUI (141) GUIDE (8) Handle graphics (78) HG2 (34) Hidden property (51) HTML (26) Icons (9) Internal component (39) Java (178) JavaFrame (20) JIDE (19) JMI (8) Listener (17) Malcolm Lidierth (8) MCOS (11) Memory (13) Menubar (9) Mex (14) Optical illusion (11) Performance (78) Profiler (9) Pure Matlab (187) schema (7) schema.class (8) schema.prop (18) Semi-documented feature (6) Semi-documented function (33) Toolbar (14) Toolstrip (13) uicontrol (37) uifigure (8) UIInspect (12) uitools (20) Undocumented feature (187) Undocumented function (37) Undocumented property (20)
Recent Comments
  • Nicholas (6 days 13 hours ago): Hi Yair, Thanks for the reply. I am on Windows 10. I also forgot to mention that this all works wonderfully out of the editor. It only fails once compiled. So, yes, I have tried a...
  • Nicholas (6 days 13 hours ago): Hi Yair, Thanks for the reply. I am on Windows 10. I also forgot to mention that this all works wonderfully out of the editor. It only fails once compiled. So, yes, I have tried a...
  • Yair Altman (6 days 20 hours ago): Nicholas – yes, I used it in a compiled Windows app using R2022b (no update). You didn’t specify the Matlab code location that threw the error so I can’t help...
  • Nicholas (7 days 16 hours ago): Hi Yair, Have you attempted your displayWebPage utility (or the LightweightHelpPanel in general) within a compiled application? It appears to fail in apps derived from both R2022b...
  • João Neves (10 days 21 hours ago): I am on matlab 2021a, this still works: url = struct(struct(struct(struct(hF ig).Controller).PlatformHost). CEF).URL; but the html document is empty. Is there still a way to do...
  • Yair Altman (13 days 19 hours ago): Perhaps the class() function could assist you. Or maybe just wrap different access methods in a try-catch so that if one method fails you could access the data using another...
  • Jeroen Boschma (13 days 22 hours ago): Never mind, the new UI components have an HTML panel available. Works for me…
  • Alexandre (13 days 23 hours ago): Hi, Is there a way to test if data dictionnatry entry are signal, simulink parameters, variables … I need to access their value, but the access method depends on the data...
  • Nicholas (14 days 13 hours ago): In case anyone is looking for more info on the toolbar: I ran into some problems creating a toolbar with the lightweight panel. Previously, the Browser Panel had an addToolbar...
  • Jeroen Boschma (17 days 20 hours ago): I do not seem to get the scrollbars (horizontal…) working in Matlab 2020b. Snippets of init-code (all based on Yair’s snippets on this site) handles.text_explorer...
  • Yair Altman (45 days 22 hours ago): m_map is a mapping tool, not even created by MathWorks and not part of the basic Matlab system. I have no idea why you think that the customizations to the builtin bar function...
  • chengji chen (46 days 5 hours ago): Hi, I have tried the method, but it didn’t work. I plot figure by m_map toolbox, the xticklabel will add to the yticklabel at the left-down corner, so I want to move down...
  • Yair Altman (53 days 22 hours ago): @Alexander – this is correct. Matlab stopped including sqlite4java in R2021b (it was still included in 21a). You can download the open-source sqlite4java project from...
  • Alexander Eder (59 days 17 hours ago): Unfortunately Matlab stopped shipping sqlite4java starting with R2021(b?)
  • K (66 days 4 hours ago): Is there a way to programmatically manage which figure gets placed where? Let’s say I have 5 figures docked, and I split it into 2 x 1, I want to place 3 specific figures on the...
Contact us
Captcha image for Custom Contact Forms plugin. You must type the numbers shown in the image
Undocumented Matlab © 2009 - Yair Altman
This website and Octahedron Ltd. are not affiliated with The MathWorks Inc.; MATLAB® is a registered trademark of The MathWorks Inc.
Scroll to top