uitable – Undocumented Matlab https://undocumentedmatlab.com/blog_old Charting Matlab's unsupported hidden underbelly Thu, 27 Oct 2022 10:42:32 +0000 en-US hourly 1 https://wordpress.org/?v=4.4.1 treeTablehttps://undocumentedmatlab.com/blog_old/treetable https://undocumentedmatlab.com/blog_old/treetable#comments Tue, 06 Aug 2013 07:10:20 +0000 https://undocumentedmatlab.com/?p=4062 Related posts:
  1. Uitable sorting Matlab's uitables can be sortable using simple undocumented features...
  2. Uitable customization report Matlab's uitable can be customized in many different ways. A detailed report explains how. ...
  3. FindJObj GUI – display container hierarchy The FindJObj utility can be used to present a GUI that displays a Matlab container's internal Java components, properties and callbacks....
  4. Plot-type selection components Several built-in components enable programmatic plot-type selection in Matlab GUI - this article explains how...
]]>
Since Matlab 7.0 (R14), Matlab has included a built-in GUI table control (uitable), at first as a semi-documented function and in release 7.6 (R2008a) as a fully-documented function. Useful as this control is, it lacks many features that are expected in modern GUIs, including sorting, filtering, cell-specific appearance and behavior, gridline customization etc. In past articles I have explained how uitable can be customized to achieve a more professional-looking table. I expanded on this in my book and my detailed uitable customization report.

Today I explain how a grouping hierarchy can be achieved in a table control that can be used in Matlab GUI. Such a control, which is a combination of a uitree and uitable, is typically called a tree-table. We can find numerous examples of it in everyday usage. I have encapsulated the functionality in a utility called treeTable on the Matlab File Exchange (#42946). The utility is provided with full source code and open-source license, and readers are welcome to use and modify it. A detailed explanation of the technicalities follows below, but if you’re just interested in having a sortable, rearrangeable, customizable, groupable table control, then all you need to do is download and use the utility.

treeTable utility

treeTable utility

headers = {'ID','Label','Logical1','Logical2','Selector','Numeric'};
data = {1,'M11',true, false,'One', 1011;  ...
        1,'M12',true, true, 'Two', 12;   ...
        1,'M13',false,false,'Many',13.4; ...
        2,'M21',true, false,'One', 21;  ...
        2,'M22',true, true, 'Two', 22;   ...
        3,'M31',true, true, 'Many',31;   ...
        3,'M32',false,true, 'One', -32;  ...
        3,'M33',false,false,'Two', 33; ...
        3,'M34',true, true, 'Many',34;  ...
};
selector = {'One','Two','Many'};
colTypes = {'label','label','char','logical',selector,'double'};
colEditable = {true, true, true, true, true}
icons = {fullfile(matlabroot,'/toolbox/matlab/icons/greenarrowicon.gif'), ...
         fullfile(matlabroot,'/toolbox/matlab/icons/file_open.png'), ...
         fullfile(matlabroot,'/toolbox/matlab/icons/foldericon.gif'), ...
}
 
% Create the table in the current figure
jtable = treeTable('Container',gcf, 'Headers',headers, 'Data',data, ...
                   'ColumnTypes',colTypes, 'ColumnEditable',colEditable, ...
                   'IconFilenames',icons, 'Groupable',true, 'InteractiveGrouping',false);
 
% Collapse Row #6, sort descending column #5 (both are 0-based)
jtable.expandRow(5,false);  % 5=row #6; false=collapse
jtable.sortColumn(4,true,false);  % 4=column #5; true=primary; false=descending

The basic implementation concept

Unfortunately, uitable as-is cannot be customized to have groupable rows. It derives from JIDE’s SortableTable, rather than one of its groupable derived classes. On the other hand, uitree (don’t you agree that after a decade of this so-useful function being semi-documented it ought to be made official?) uses a different class hierarchy outside com.jidesoft.grid, and so it cannot be easily customized to display rows (as opposed to simple labels).

These limitations mean that we cannot use uitable or uitree and need to use a custom component. Luckily, such a component is available in all Matlab installations, on all platforms. It is part of the grid components package, on which Matlab GUI has relied for many years, by JIDE Software. JIDE Grids is a collection of components that extend the standard Java Swing JTable component, and is included in each Matlab installation (/java/jarext/jide/jide-grids.jar under the Matlab root). I discussed multiple JIDE controls in this blog over the years. You can find further details on JIDE Grids in the Developer Guide and the Javadoc documentation.

In fact, there are no less than three different components that we could use in our case: TreeTable, GroupTable and HierarchicalTable:

JIDE Grids class hierarchy (we normally use only one of the marked classes)

JIDE Grids class hierarchy (we normally use only one of the marked classes)

Note that we cannot use PropertyTable since that component is limited to only two columns. This is perfect for presenting property names and values, which is the reason it is used by Matlab’s inspect function and my generic propertiesGUI utility or Levente Hunyadi’s Property Grid utility. But in this case we wish to display a general multi-column table, so PropertyTable is a no-go.

TreeTable and GroupTable enable data rows that have similar type (class), whereas HierarchicalTable enables more flexibility, by allowing display of any component type (including full tables) in child rows. This flexibility comes with a price that customizing a HierarchicalTable is more difficult than TreeTable or GroupTable. These latter two components are quite similar; we use GroupTable, which extends TreeTable with the ability to automatically group rows that have the same value in a certain column.

Data model

The above-mentioned table classes all derive from SortableTable (which also underlies uitable). Unfortunately, something in the Matlab-Java interface breaks the ability of the JIDE table classes (or rather, their data model) to understand numeric values for what they are. As a result, sorting columns is done lexically, i.e. “123” < “34” < “9”. To fix this, I’ve included a custom Java table model (MultiClassTableModel) with the treeTable utility, which automatically infers the column type (class) based on the value in the top row (by overriding the getColumnClass() method).

Using this new class is pretty easy:

% Create the basic data-type-aware model using our data and headers
javaaddpath(fileparts(mfilename('fullpath')));  % add the Java class file to the dynamic java class-path
model = MultiClassTableModel(data, headers);  % data=2D cell or numeric array; headers=cell array of strings
 
% Wrap the standard model in a JIDE GroupTableModel
com.mathworks.mwswing.MJUtilities.initJIDE;  % initialize JIDE
model = com.jidesoft.grid.DefaultGroupTableModel(model);
model.addGroupColumn(0);  % make the first column the grouping column
model.groupAndRefresh;  % update the model data
 
% Use the generated model as the data-model of a JIDE GroupTable
jtable = eval('com.jidesoft.grid.GroupTable(model);');  % prevent JIDE alert by run-time (not load-time) evaluation
jtable = handle(javaObjectEDT(jtable), 'CallbackProperties');  % ensure that we're using EDT
 
% Enable multi-column sorting
jtable.setSortable(true);
 
% Present the tree-table within a scrollable viewport on-screen
scroll = javaObjectEDT(JScrollPane(jtable));
[jhscroll,hContainer] = javacomponent(scroll, tablePosition, hParent);
set(hContainer,'units', 'normalized','pos',[0,0,1,1]);  % this will resize the table whenever its container is resized

Here, com.mathworks.mwswing.MJUtilities.initJIDE is called to initialize JIDE’s usage within Matlab. Without this call, we may see a JIDE warning message in some Matlab releases. We only need to initJIDE once per Matlab session, although there is no harm in repeated calls.

javacomponent is the undocumented built-in Matlab function that adds Java Swing components to a Matlab figure, using the given dimensions and parent handle. I discussed it here.

Callbacks

There are two main callbacks that can be used with treeTable:

  • table data update – this can be set by uncommenting line #237 of treeTable.m:
    set(handle(getOriginalModel(jtable),'CallbackProperties'), 'TableChangedCallback', {@tableChangedCallback, jtable});

    which activates the sample tableChangedCallback() function (lines #684-694). Naturally, you can also set your own custom callback function.

    % Sample table-editing callback
    function tableChangedCallback(hModel,hEvent,jtable)
        % Get the modification data
        modifiedRow = get(hEvent,'FirstRow');
        modifiedCol = get(hEvent,'Column');
        label   = hModel.getValueAt(modifiedRow,1);
        newData = hModel.getValueAt(modifiedRow,modifiedCol);
     
        % Now do something useful with this info
        fprintf('Modified cell %d,%d (%s) to: %s\n', modifiedRow+1, modifiedCol+1, char(label), num2str(newData));
    end  % tableChangedCallback
  • row selection update – this is currently enabled in line #238 of treeTable.m:
    set(handle(jtable.getSelectionModel,'CallbackProperties'), 'ValueChangedCallback', {@selectionCallback, jtable});

    which activates the sample selectionCallback() function (lines #696-705). Naturally, you can also set your own custom callback function.

    % Sample table-selection callback
    function selectionCallback(hSelectionModel,hEvent,jtable)
        % Get the selection data
        MinSelectionIndex  = get(hSelectionModel,'MinSelectionIndex');
        MaxSelectionIndex  = get(hSelectionModel,'MaxSelectionIndex');
        LeadSelectionIndex = get(hSelectionModel,'LeadSelectionIndex');
     
        % Now do something useful with this info
        fprintf('Selected rows #%d-%d\n', MinSelectionIndex+1, MaxSelectionIndex+1);
    end  % selectionCallback

Some useful features of treeTable

treeTable with InteractiveGrouping, multi-column sorting, column rearranging

treeTable with interactive grouping, multi-column sorting, column rearranging

  • Sortable columns (including numeric columns)
  • Rearrangeable columns (drag headers left/right)
  • Auto-fit the table columns into the specified container width
  • Manually resize columns by dragging the column divider gridlines (not just the header dividers as in uitable)
  • Flat or groupable table, based on the specified Groupable parameter (default=true)
  • Ability to interactively group columns (just like Microsoft Outlook) using the InteractiveGrouping parameter (default=false)
  • Selector cells only show the drop-down arrow of the currently-selected cell (unlike uitable which shows it for all the column cells)
  • Selector cells enable editing, unlike uitable that only enables selecting among pre-defined values
  • Ability to attach user-defined icons for the leaf rows and the grouping rows (expanded/collapsed)
  • Easily attach custom cell editors or renderers to any table column (see my book and my detailed uitable customization report for details)

All of these features can be turned on/off using the control’s properties. Again, see my book or report for details (or ask me to do it for you…).

I remind readers that I will be visiting clients in Austria (Vienna, Salzburg) and Switzerland (Zurich) in August 18-29. If you live in the area, I will be happy to meet you to discuss how I could bring value to your needs, as consultant, contractor or trainer (more details).

]]>
https://undocumentedmatlab.com/blog_old/treetable/feed 85
Real-time trading system demohttps://undocumentedmatlab.com/blog_old/real-time-trading-system-demo https://undocumentedmatlab.com/blog_old/real-time-trading-system-demo#comments Wed, 29 May 2013 13:15:21 +0000 https://undocumentedmatlab.com/?p=3825 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. GUI integrated browser control A fully-capable browser component is included in Matlab and can easily be incorporated in regular Matlab GUI applications. This article shows how....
  4. Uitab colors, icons and images Matlab's semi-documented tab panels can be customized using some undocumented hacks...
]]>
Last week I gave a presentation at the MATLAB Computational Finance Conference in New York. The room was packed-full with close to 200 professionals in the finance industry. The energy and feedback were tremendous, it was a great experience. The presentation (PDF format) is provided here.

I presented a demo application that showed how Matlab can be used to create a full end-to-end trading system, highlighting Matlab’s potential as a platform of choice. I used Interactive Brokers to demonstrate live market data feed and account/portfolio input, as well as for sending trading orders to the market, via the IB-Matlab connector:

Real-time trading system demo in Matlab (click for details)

Real-time trading system demo in Matlab (click for details)

The demo system’s user interface showcased the hidden visualization and interactivity potential of MATLAB for tracking order executions and charting financial time-series in real time. The undocumented features used in the demo include:

The demo source code is provided here (tradingDemo.m and supporting files). Note that this is provided as-is, free of charge but without any warranty or support. You would naturally need IB-Matlab and an Interactive Brokers account to run it.

If you came to the conference, I want to thank you for being an excellent audience. I hope we have a chance to work together on your projects. Shoot me an email if you’d like my help in any consulting, training or development work.

]]>
https://undocumentedmatlab.com/blog_old/real-time-trading-system-demo/feed 1
Multi-line uitable column headershttps://undocumentedmatlab.com/blog_old/multi-line-uitable-column-headers https://undocumentedmatlab.com/blog_old/multi-line-uitable-column-headers#comments Wed, 27 Jun 2012 22:54:40 +0000 https://undocumentedmatlab.com/?p=2976 Related posts:
  1. Spicing up Matlab uicontrol tooltips Matlab uicontrol tooltips can be spiced-up using HTML and CSS, including fonts, colors, tables and images...
  2. Rich-contents log panel Matlab listboxes and editboxes can be used to display rich-contents HTML-formatted strings, which is ideal for log panels. ...
  3. Aligning uicontrol contents Matlab uicontrols can often be customized using plain HTML/CSS, without need for advanced Java. ...
  4. Displaying animated GIFs It is possible to easily display animated images in Matlab figure windows. ...
]]>
I often need to present data in tabular format in Matlab GUI, and this data often has relatively long column headers such as “Maximal draw/gain” or “Coefficient of elasticity”. When the table has many columns, these long column headers do not fit in the small space that is available:

uitable('data',magic(2),'ColumnName',{'Maximal draw/gain','Coefficient of elasticity'})

Default uitable behavior with long headers

Default uitable behavior with long headers

Creating multi-line headers

It makes sense to split such long column headers into a multi-line string. In the new (R2008a+) uitable, this can easily be done by adding the | character wherever we wish the line to be split; in both the new and the old uitable, we can also use the built-in HTML support by adding a simple <br/>. The following code snippet demonstrates both of these alternatives:

uitable('data',magic(2), 'ColumnName',{'Maximal|draw/gain', '<html><center />Coefficient<br />of elasticity</html>'});

Multi-line uitable headers

Multi-line uitable headers

Much more readable and useful, I think. Note that HTML code is left-aligned by default, so to center the header I added the <center> tag in the snippet.

If the text appears too crowded in the header cells, we can slightly reduce the header font, to make it appear more spaced-out. The following snippet illustrates this for the old uitable (available since Matlab 7.0 all the way until today), which can only use the HTML alternative since it does not support |:

headers = {'<html>Maximal<br />draw/gain</html>', ...
           '<html><center /><font size=-2>Coefficient<br />of elasticity</font></html>'};
uitable('v0','data',magic(2),'ColumnNames',headers);

Multi-line headers in the old uitable

Multi-line headers in the old uitable

Dynamic multi-line headers

While adding | or <br/> solves the problem for the majority of cases, it is sometimes difficult to know in advance where to place the line-split. This often happens when the column headers are dynamically generated by the program. If we omit the <br/> from our header strings, we get sub-optimal rendering: The new uitable simply hides all overflow terms, and the old uitable pushes them to the bottom:

headers = {'<html>Maximal draw/gain</html>', ...
           '<html><center /><font size=-2>Coefficient of elasticity</font></html>'};
uitable('v0','data',magic(2),'ColumnNames',headers);

Default dynamic HTML multi-line (old uitable)

Default dynamic HTML multi-line (old uitable)

I’ve tried numerous things, including CSS wrapping directives etc. None seem to work (I’ll be happy to hear a new idea that does work), except for the following weird-sounding trick: add a “<br/>&nbsp;” at the end of the HTML header string. If the column is wide enough, then this will be disregarded; otherwise, it will automatically split the string nicely:

headers = {'<html>Maximal draw/gain<br />&nbsp;</html>', ...
           '<html><center /><font size=-2>Coefficient of elasticity<br />&nbsp;</font></html>'};
uitable('v0','data',magic(2),'ColumnNames',headers);

Nicely-behaved dynamic HTML multi-lines

Nicely-behaved dynamic HTML multi-lines

Note: the &nbsp; part is important – the trick will NOT work without it!

Controlling the headers

HTML provides some degree of control over the table header row. Some additional aspects can be configured by accessing the underlying Java’s TableHeader sub-component. But here’s another trick that I found handy: I hide the table header row altogether, and use the top table data row for my headers. I can control this row’s height using JTable’s standard setRowHeight() method. Using some fancy cell background colors I can make this row stand out, and I can easily control other aspects as well.

The same trick can also be used for the row-header column: I can dispense with the standard one and use the table’s first column as a row-header column.

For more information on uitable customization, refer to section 4.1 of my Matlab-Java book, or to my uitable customization report.

Do you have a favorite trick with multi-line strings in Matlab GUI? If so, please share it in a comment below.

]]>
https://undocumentedmatlab.com/blog_old/multi-line-uitable-column-headers/feed 19
Uitable cell colorshttps://undocumentedmatlab.com/blog_old/uitable-cell-colors https://undocumentedmatlab.com/blog_old/uitable-cell-colors#comments Thu, 27 Oct 2011 01:51:53 +0000 https://undocumentedmatlab.com/?p=2476 Related posts:
  1. Uitable customization report Matlab's uitable can be customized in many different ways. A detailed report explains how. ...
  2. Tri-state checkbox Matlab checkboxes can easily be made to support tri-state functionality....
  3. GUI integrated browser control A fully-capable browser component is included in Matlab and can easily be incorporated in regular Matlab GUI applications. This article shows how....
  4. Customizing listbox & editbox scrollbars Matlab listbox and multi-line editbox uicontrols have pre-configured scrollbars. This article shows how they can be customized....
]]>
A client recently asked me to develop an application that will help discover technical indicators for trading on the stock market. The application was very data-intensive and the analysis naturally required visual presentations of number-crunching results in a readable manner. One of the requirements was to present numeric results in a data table, so we naturally use uitable for this.

Today I will show how using some not-so-complex Java we can transform the standard Matlab uitable into something much more useful.

First pass – basic data table

We start by displaying the data in a simple uitable. The essence of the relevant code snippet was something like this:

headers = {'Periods', ...
           '<html><center>Any period<br />returns</center></html>', ...
           '<html><center>Avg return<br />signal</center></html>', ...
           '<html><center>Avg<br />gain</center></html>', ...
           '<html><center>Avg<br />draw</center></html>', ...
           '<html><center>Gain/draw<br />ratio</center></html>', ...
           '<html><center>Max<br />gain</center></html>', ...
           '<html><center>Max<br />draw</center></html>', ...
           '<html><center>Random<br />% pos</center></html>', ...
           '<html><center>Signal<br />% pos</center></html>', ...
           'Payout', '% p-value'};
hTable = uitable('Data',data, 'ColumnEditable',false, ...
           'ColumnName',headers, 'RowName',[], ...
           'ColumnFormat',['numeric',repmat({'bank'},1,11)], ...
           'ColumnWidth','auto', ...
           'Units','norm', 'Position',[0,.75,1,.25]);

Plain data table - so boooooring...

Plain data table - so boooooring...

We can see from this simple example how I have used HTML to format the header labels into two rows, to enable compact columns. I have already described using HTML formatting in Matlab controls in several articles on this website. I have not done this here, but you can easily use HTML formatting for other effect such as superscript (<sup>), subscript (<sub>), bold (<b>), italic (<i>), font sizes and colors (<font>) and other standard HTML effects.

Even with the multi-line headers, the default column width appears to be too wide. This is apparently an internal Matlab bug, not taking HTML into consideration. This causes only part of the information to be displayed on screen, and requires the user to either scroll right and left, or to manually resize the columns.

Second pass – auto-resizing that actually works…

To solve the auto-resizing issue, we resort to a bit of Java magic powder. We start by using the findjobj utility to get the table’s underlying Java reference handle. This is the containing scrollpane, and we are interested in the actual data table inside. We then use the setAutoResizeMode, as described in the official Java documentation.

jScroll = findjobj(hTable);
jTable = jScroll.getViewport.getView;
jTable.setAutoResizeMode(jTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);

Auto-resized columns that actually work

Auto-resized columns that actually work

Third pass – adding colors

There 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 several other fixes that may seem trivial by themselves but together giver a much more stylish look to the table’s look and feel. I’ll skip these for now (interested readers can read all about them, and more, in my detailed uitable customization report).

One of the more important customizations is to add colors depending on the data. In my client’s case, there were three requirements:

  • data that could be positive or negative should be colored in green or red foreground color respectively
  • large payouts (abs > 2) should be colored in blue
  • data rows that have statistical significance (%p-value < 5) should have a yellow background highlight

While we could easily use HTML or CSS formatting to do this, this would be bad for performance in a large data table, may cause some issues when editing table cells or sorting columns. I chose to use the alternative method of cell renderers.

ColoredFieldCellRenderer is a simple table cell renderer that enables setting cell-specific foreground/background colors and tooltip messages (it also has a few other goodies like smart text alignment etc.). This requires some Java knowledge to program, but in this case you can simply download the ColoredFieldCellRenderer.zip file and use it, even if you don’t know Java. The source code is included in the zip file, for anyone who is interested.

After using javaaddpath to add the zip file to the dynamic Java classpath (you can add it to the static classpath.txt file instead), the contained Java class file is available for use in Matlab. We configure it according to our data and then assign it to all our table’s columns.

Java savvy readers might complain that the data-processing should perhaps be done in the renderer class rather than in Matlab. I have kept it in Matlab because this would enable very easy modification of the highlighting algorithm, without any need to modify the generic Java renderer class.

Unfortunately, in the new uitable design (the version available since R2008a), JIDE and Matlab have apparently broken the standard MVC approach by using a table model that not only controls the data but also sets the table’s appearance (row-striping background colors, for example), and disregards column cell-renderers. In order for our custom cell renderer to have any effect, we must therefore replace Matlab’s standard DefaultUIStyleTableModel with a simple DefaultTableModel. This in itself is not enough – we also need to ensure that the uitable has an empty ColumnFormat property, because if it is non-empty then it overrides our cell-renderer.

In the following code, note that Java row and column indices start at 0, not at 1 like in Matlab. We need to be careful about indices when programming java in Matlab.

The rest of the code should be pretty much self explanatory (again – more details can be found in the above-mentioned report):

% Initialize our custom cell renderer class object
javaaddpath('ColoredFieldCellRenderer.zip');
cr = ColoredFieldCellRenderer(java.awt.Color.white);
cr.setDisabled(true);  % to bg-color the entire column
 
% Set specific cell colors (background and/or foreground)
for rowIdx = 1 : size(data,1)
 
  % Red/greed foreground color for the numeric data
  for colIdx = 2 : 8
    if data(rowIdx,colIdx) < 0
      cr.setCellFgColor(rowIdx-1,colIdx-1,java.awt.Color(1,0,0));    % red
    elseif data(rowIdx,colIdx) > 0
      cr.setCellFgColor(rowIdx-1,colIdx-1,java.awt.Color(0,0.5,0));  % green
    end
  end
 
  % Yellow background for significant rows based on p-value
  if data(rowIdx,12) < = 5 && data(rowIdx,11)~=0
    for colIdx = 1 : length(headers)
      cr.setCellBgColor(rowIdx-1,colIdx-1,java.awt.Color(1,1,0));    % yellow
    end
  end
 
  % Bold blue foreground for significant payouts
  if abs(data(rowIdx,11)) >= 2
    cr.setCellFgColor(rowIdx-1,10,java.awt.Color(0,0,1));    % blue
 
    % Note: the following could easily be done in the renderer, just like the colors
    boldPayoutStr = ['<html><b>' num2str(data(rowIdx,11),'%.2f') '</b></html>'];
    %jTable.setValueAt(boldPayoutStr,rowIdx-1,10);  % this is no good: overridden when table model is replaced below...
    dataCells{rowIdx,11} = boldPayoutStr;
  end
end
 
% Replace Matlab's table model with something more renderer-friendly...
jTable.setModel(javax.swing.table.DefaultTableModel(dataCells,headers));
set(hTable,'ColumnFormat',[]);
 
% Finally assign the renderer object to all the table columns
for colIdx = 1 : length(headers)
  jTable.getColumnModel.getColumn(colIdx-1).setCellRenderer(cr);
end

Finally something lively!

Finally something lively!

This may not take a beauty contest prize, but you must admit that it now looks more useful than the original table at the top of this article.

]]>
https://undocumentedmatlab.com/blog_old/uitable-cell-colors/feed 115
Uitable customization reporthttps://undocumentedmatlab.com/blog_old/uitable-customization-report https://undocumentedmatlab.com/blog_old/uitable-customization-report#comments Wed, 03 Aug 2011 18:00:25 +0000 https://undocumentedmatlab.com/?p=2396 Related posts:
  1. Uitable sorting Matlab's uitables can be sortable using simple undocumented features...
  2. Date selection components The JIDE package, pre-bundled in Matlab, contains several GUI controls for selecting dates - this article explains how they can be used...
  3. Tri-state checkbox Matlab checkboxes can easily be made to support tri-state functionality....
  4. Font selection components Several built-in components enable programmatic font selection in Matlab GUI - this article explains how. ...
]]>
In last week’s report about uitable sorting, I offered a report that I have written which covers uitable customization in detail. Several people have asked for more details about the contents of this report. This is a reasonable request, and so in today’s post I will discuss in a bit more detail the highlights of what can be achieved to customize Matlab uitables. For the fine details, well, get my uitable report (45 pages PDF, $25).

1. Introduction

Here I discuss the evolution of the uitable control over the past decade, from its initially semi-documented status to today. I explain the similarities and differences between the control’s versions and explain how they can both be accessed today.

I also provide references to online resources for both Matlab’s uitable‘s underlying Java components, as well as multiple alternatives using different technologies, that have been used and reported over the years.

2. Customizing uitable

In this section I explore the sub-component hierarchy of the uitable controls. I show how the scrollbar sub-components can be accessed (this will be used in section 4 below), as well as the table header and data grid. This is the entry point for uitable customization.

annotated uitable sub-components

annotated uitable sub-components

I explain how individual cells can be modified without requiring the entire data set to be updated. This is very important in large data sets, to prevent flicker and improve performance.

I show how HTML can be used to format data cell contents (even images) and tooltips:

uitable with HTML cell contents and tooltip

uitable with HTML cell contents and tooltip


uitable with cell images

uitable with cell images

3. Cell renderers and cell editors

This section explains the role of the cell-renderer in the visual appearance of the cell, and of cell-editors in the way that cells interact with the user for data modification. I explain such customizations from the simple (setting a column’s background color) to the complex (cell-specific tooltips and colors; color-selection cell-editor):


uitable with a non-standard cell-renderer

uitable with a non-standard cell-renderer


uitable with a non-standard cell-rendereruitable with a non-standard cell-editor

uitable with a non-standard cell-renderer (left) and cell-editor (right)


uitable with custom CellRenderer and CellEditor

uitable with custom CellRenderer and CellEditor

Cell renderers can also be used to set custom text format of cell contents and cell-specific tooltips (note the top table in the following screenshot):

uitable with custom CellRenderers (note text formats and cell-specific tooltips)

uitable with custom CellRenderers (note text formats and cell-specific tooltips)


(also note the colored table headers in the bottom table)

4. Table callbacks

This section of my uitable report presents the different callback properties that are settable in the old and new uitable, for events such as cell selection, data modification, key press, and mouse click. The discussion includes a working code example for validating user input and reverting invalid edits. The section also includes a discussion of how to avoid and overcome problems that may occur with the callback execution.

5. Customizing scrollbars, column widths and selection behavior

This section explains how to control the scrollbars behavior. For example, hiding the horizontal (bottom) scrollbar, automatically displaying it when the data width is larger than the table width. I also show how to control the column widths.

I then show how to customize the data selection policy: Can multiple cells be selected? perhaps only one cell at a time? or maybe a single large interval of cells? – this is all customizable. I then explain how the selection can be done and accessed programmatically. Ever wanted to set the cursor on cell A1 after some system event has occurred? – this will show you how to do it. Ever wanted to use non-standard selection colors (background/foreground)? – this can also be done.

6. Data sorting

Table sorting was discussed in last week’s article. This section expands on that article, and explains how the sorting can be customized, controlled, and accessed programmatically, and how sorted rows can be retrieved by the user.

Multi-column sorting with blue sort-order numbers

Multi-column sorting with blue sort-order numbers

7. Data filtering

Data filtering is the ability to filter only a specified sub-set of rows for display (just like in Excel). This section explains how to do it (it’s so easy!).

uitable data filtering

uitable data filtering

8. JIDE customizations

The new uitable is based on an underlying JIDE table. This sectino explains how we can use this to our advantage for some simple and useful. Customization.

For example: have you wondered some time why is it that columns can only be resized by dragging the tiny divider in the table header? Why can’t the columns and rows be resized by dragging the grid lines? Well, it turns out that they can, with just a tiny bit of JIDE magic powder, explained here:

Resizing columns

Resizing columns

Similarly, this section explains how we can use JIDE to merge together adjacent cells:

Example of two table cell-spans (1x2 and 2x2)

Example of two table cell-spans (1x2 and 2x2)

I also show how to attach a custom context-menu (right-click menu) to the table header row:

Custom header-row context-menu

Custom header-row context-menu

9. Controlling the table structure (adding/removing rows)

This section discusses the matter of dynamically adding and removing table rows. While this is easy to do in the old uitable, this is unfortunately not the case in the new uitable.

10. Run-time performance

This section discusses ways to improve the run-time performance (speed) of uitable, both new and old. For additional information regarding run-time performance, refer to my book “MATLAB Performance Tuning“.

11. Final remarks

Here I present a workaround for a long-time table bug. Also, I present my createTable utility that wraps table creation in Matlab:

createTable utility screenshot (note the action buttons, sortable columns, and customized CellEditor)

createTable utility screenshot (note the action buttons, sortable columns, and customized CellEditor)

Appendix – JIDE Grids

Finally, this appendix presents an overview of the wide array of components provided by JIDE and available in Matlab. uitable uses only one of these components (the SortableTable). In fact, there are many more such controls that we can use in our GUIs.

These include a wide selection of combo-box (drop-down) controls – calculator, file/folder selection, date selection, color selection, multi-elements selection etc.

Date selection comb-box

Date selection combo-box

In addition, a very wide selection of lists, trees and table types is available.

TreeTable example

TreeTable example

Also included is a set of specialized editbox controls for accepting IP addresses and credit card numbers:

IP address entry boxcredit-card entry boxcredit-card entry box

IP address and credit-card entry boxes

While not explaining all these controls in detail (this could take hundreds of pages), this section does say a few words on each of them, and includes links to online resources for further exploration.

]]>
https://undocumentedmatlab.com/blog_old/uitable-customization-report/feed 74
Uitable sortinghttps://undocumentedmatlab.com/blog_old/uitable-sorting https://undocumentedmatlab.com/blog_old/uitable-sorting#comments Tue, 26 Jul 2011 18:00:01 +0000 https://undocumentedmatlab.com/?p=2391 Related posts:
  1. Uitable customization report Matlab's uitable can be customized in many different ways. A detailed report explains how. ...
  2. Tab panels – uitab and relatives This article describes several undocumented Matlab functions that support tab-panels...
  3. treeTable A description of a sortable, groupable tree-table control that can be used in Matlab is provided. ...
  4. Types of undocumented Matlab aspects This article lists the different types of undocumented/unsupported/hidden aspects in Matlab...
]]>
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

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);

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
]]>
https://undocumentedmatlab.com/blog_old/uitable-sorting/feed 46