- Undocumented Matlab - https://undocumentedmatlab.com -

Uitable customization report

Posted By Yair Altman On August 3, 2011 | 81 Comments

In last week’s report about uitable sorting [1], 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 [2] (45 pages PDF, $29).

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 [1]. 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 section 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 [3]“.

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.

Categories: GUI, Java, Medium risk of breaking in future versions, Stock Matlab function, Undocumented feature


81 Comments (Open | Close)

81 Comments To "Uitable customization report"

#1 Comment By S On August 9, 2011 @ 02:47

Hi Yair
thank you for this article.
I am trying to use uitable as a simple line vector editor in a GUI.
and I wuld like to be able to remove the ‘column names’ line from the display, to be able to see only the data grid.
Do you know if such option is available? How would you do this?
Maybe there is a simpler way to edit datas (I want to avoid using edit text control in this particular case)
Hope this was clear
Thank you!

#2 Comment By Yair Altman On August 10, 2011 @ 14:30

@Simon – uitable header row and header column customizations are explored in detail in my [10]

#3 Comment By Marcel On August 24, 2011 @ 23:24

Hallo Yair,
we are interested in nicely formatted tables which can be printed or pasted into word reports. Does your article cover formatting like double or bold lines between cells or merging cells?
Is it possible to print your tables correctly on a printer or in an emf file?
Thanks for your brilliant web site.
Marcel

#4 Comment By Yair Altman On August 25, 2011 @ 00:24

@Marcel – it’s not “my” tables, it’s Matlab’s/Java’s. Printing works regularly. The report covers cell merging but not changing the grid lines. If you want precise control of Word tables, including cell-border formatting etc., please contact me offline, using my email link (see top-right of this webpage).

#5 Comment By Eero Kuusi On September 1, 2011 @ 07:31

Hi Yair! Thanks for all the material you have here, these have proven very useful. I just bought the report yesterday, but have a question regarding listboxes: Is there some easy way of changing the background color of a certain line? Using HTML I’ve achieved this, but the background color ends where the string stops, so strings with different length appear with uneven color bars. An ugly workaround Ive used is to use a fixed length font and put in whitespaces after each string to even the character length or to just insert a lot of whitespaces after each string to make the background extend beyond the listbox, but neither solution gives a faultless look.

Basically, what I want is to be able to doubleclick on a listbox entry which would color that entry with a preset color to show that it is selected.

#6 Comment By quant On October 21, 2011 @ 07:44

hi Yair,

I bought your report. I was trying to implement my own sorting routine by using SortChangedCallback property. Unfortunately, when I look into it, I could not find which column is being sorted. How to find that out ?? Please let me know which property I need to look at.

Thanks

#7 Comment By Yair Altman On October 22, 2011 @ 09:57

Look at the bottom of page 23…, specifically: getSortingColumns()

#8 Comment By Matthias On January 31, 2012 @ 16:10

Hi Yiar,

first thanks for all the information.

Second a question regarding your work with JTables. I’ve seen in this post, that you include a checkbox in a single cell –> that’s what I’m looking for. I guess you are describing how it works in your report?

The question is, I ordered your book an few weeks ago and hope it will arrive soon. Do I need the report or do I get the information I need in your book?
Thanks and best regards
Matthias

#9 Comment By Yair Altman On January 31, 2012 @ 16:57

@Matthias, the book covers almost the entire report, except a few additions/fixes that are newer in the report. For example, the sorting and filtering sections have been expanded with some new information. Also, the report is softcopy PDF, so you can copy/paste/search. The report is also in full color, and is available immediately via reply email.

On the other hand, the book contains a lot of other stuff, not related to the report, so they complement one another.

#10 Comment By Harold On February 15, 2012 @ 00:25

Is there a way to use leading zeros and commas for cells in MATLAB’s uitable using the GUIDE. For example, I would like to make a table as follows.

0,1,0 2,4,3 0,5,6

1,2,3 5,0,1 0,0,0

0,3,0 4,3,1 5,5,5

The number of columns and rows are arbitrary. The user will enter in how many (x,y,z) coordinates are in the u direction (columns) and how many (x,y,z) coordinates are in the v direction (rows) Each cell should contain three numbers, x,y,z, which are separated by commas. I want to also be able to use a leading zero. I’ve tried many different ways of accomplishing this but can not figure this out.

#11 Comment By Yair Altman On February 25, 2012 @ 15:44

@Harold – enter the cell contents as strings, i.e., ‘0,1,0’ etc.

#12 Comment By Matthew On November 9, 2012 @ 06:52

I would like to use a spinner in the uitable. Is this covered in the report?

#13 Comment By Yair Altman On November 18, 2012 @ 13:39

@Matthew – using a spinner cell-editor is indeed covered in the report (section 3), but only in a brief mention, as one of many available built-in cell-editors that can be used. Additional details are in my book (section 5.7.5). Combining the information in section 5.7.5 of the book, with section 3 of the report shold get you all that you need.

#14 Comment By Marco Santos On March 22, 2013 @ 05:24

Hi Yair,

Is there any way to change the background color of the unused table area (below the existing table rows)?

I’m using matlab R14. Thanks in advance.

#15 Comment By Yair Altman On March 22, 2013 @ 05:57

@Marco – try this:

mtable.Table.getParent.setBackground(java.awt.Color.white)

#16 Comment By Shad On April 5, 2013 @ 08:15

Hello Yair,

Thanks for the great website. I have a problem involving tables with large array of data (70×60) when the data is a cell array. When I change data in a table cell and hit enter (or tab), the value in the cell goes back to the original value for almost a second before changing back to my new value. I verified that the delay scales with the size of the table, so it is nearly instantaneous with small tables (but still happens). It doesn’t happen when the data a simple double array. Do you have any idea how to change this behavior and speed it up?

#17 Comment By Yair Altman On April 5, 2013 @ 08:27

Yes – use a Java table directly, not Matlab’s uitable

#18 Pingback By Real-time trading system demo | Undocumented Matlab On May 29, 2013 @ 06:18

[…] Customized data table […]

#19 Comment By Ramiro Massol On July 2, 2013 @ 07:03

hi Yair
Sorry for not replying to you soon. I kind of figure out a workaround to the bug I mentioned before. Now I have one question about how to set up a KeyPressFcn in a GUI when an uitable occupies the whole area of the GUI. I set up the KeyPressFcn for the GUI figure, but somehow the presence of the uitable (using your createtable code) overrides it. Is there any way to indicate to change createtable to take my KeyPressFcn?
best
ramiro

#20 Comment By Yair Altman On July 3, 2013 @ 15:18

You can set up a KeyPressedCallback on the JTable

#21 Comment By ramiro massol On July 7, 2013 @ 13:23

hi Yair
I tried setting the KeyPressedCallback before contacting you but it does not respond, seems to listen only to the predefined keypress function inherent in createtable (e.g. CTRL select all).
best

#22 Pingback By treeTable | Undocumented Matlab On August 6, 2013 @ 01:08

[…] treeTable Tuesday, August 6th, 2013 Hello there! If you are new here, you might want to subscribe to the RSS feed or email feed for updates on Undocumented Matlab topics.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. […]

#23 Comment By Kevin Joosten On September 3, 2013 @ 01:00

Hello Yair,

I’m working with the createTable for a while now and it does eveything i want it to do. There is however one problem with the initialisation, sometimes the table is not visible and as far as i know at this moment only a complete restart of the GUI works. i’ve found out that when not visible the result of [~,~,check,~]=get(handles.jtable,’visibleRect’); is greater than when the table is visible. I’ve looked in the book but did not found any solution there.

Do you have any sugestions? Thanks in advance.

Kevin

#24 Comment By Kevin Joosten On September 5, 2013 @ 03:28

Maybe for future users with the same problem.
I just solved it by making the dimensions fixed, this was however not the first choice. At least it does work consistent now.
Keep up the good work Yair.
Kind regards, Kevin

#25 Pingback By Rich-contents log panel | Undocumented Matlab On September 20, 2013 @ 01:57

[…] Customized data table […]

#26 Pingback By Editbox data input validation | Undocumented Matlab On October 2, 2013 @ 10:12

[…] (Luhn’s algorithm, recently featured in a video tutorial by Doug Hull). Of course, there are dedicated JIDE controls that do much of this already, but let’s not […]

#27 Comment By Sjors Teeuwen On October 25, 2013 @ 06:58

Hi Yair,

I used the code as you suggest on page 166 of your report and the colored cell render works fine, but now the checkboxes won’t show and I don’t see any changes made to editable cells. When I leave out the third line(jtable.setModel) the colored cell render doesn’t work, but the checkboxes and the changes are available.

jscroll = findjobj(mtable);
jtable = jscroll.getViewport.getView;
jtable.setModel(javax.swing.table.DefaultTableModel(data,cols))
jtable.getColumnModel.getColumn(2).setCellRenderer(ColorCellRenderer);
jtable.getColumnModel.getColumn(2).setCellEditor(ColorCellEditor);

do you have any clue on how to fix this?

best regards,

Sjors

#28 Comment By Jacques On March 5, 2014 @ 10:09

Hello Yair,
I am using your findjobj function in my code to resize the row headers of 3 uitable elements (on the same page).
It has helped me a lot but it takes a significant time to fetch the Java object (~0.3s each time) and causes the figure to “blink” each time I use it.
I have tried commenting out the calls to pause() and drawnow() in findjobj (all but the first drawnow), reducing time down to 0.1s but the screen still flashes.
Do you know a more time-efficient way to modify this specific attribute? Or how to prevent the screen from flashing?
Thanks a lot,
Jacques L.

PS: code

function headerSize(tableHandle,width)
% get the row header
tic
jscroll=findjobj(tableHandle);
toc
rowHeaderViewport=jscroll.getComponent(4);
rowHeader=rowHeaderViewport.getComponent(0);
%resize the row header
newWidth=width;
rowHeaderViewport.setPreferredSize(java.awt.Dimension(newWidth,0));
height=rowHeader.getHeight;
rowHeader.setPreferredSize(java.awt.Dimension(newWidth,height));
rowHeader.setSize(newWidth,height);

#29 Comment By Yair Altman On March 5, 2014 @ 10:43

@Jacques – use the old (pre-2008a) uitable, which returns the Java object directly

#30 Comment By maia On April 3, 2014 @ 14:15

hi

firstly i should thank you for your good site

and second i have question: i try to display images in uitable in MATLAB-GUI. as you said I use HTML in matlab like this:

 
[filename, user_canceled] = imgetfile;
handles.pic=filename;
kk=randperm(TotallCell);
pic=handles.pic;
C(kk(i)) =({['']});
set(handles.uitable1,'Data',C);

But unfortunately the pic does not show in specified cell instead a “broken link” icon appear.

And i try everything i know to solve it but i couldn’t.

can you tell me which part i am doing wrong?

#31 Comment By Yair Altman On April 3, 2014 @ 15:00

@Maia – You’re probably not formatting your HTML image URL correctly. This is explained here: [11]

#32 Comment By maia On April 5, 2014 @ 11:26

i am sorry , i post my code wrongly

my code:

 
[filename, user_canceled] = imgetfile;
handles.pic=filename;
kk=randperm(TotallCell);
pic=handles.pic;
C(kk(i)) =({['']});
set(handles.uitable1,'Data',C);

i read your link
but in that post we assume i know image complete address but if i want let the user chose pic(image)
(the image address is not known when i write code ), is the same code that you mentioned in that post still can be used?

thank you .

#33 Comment By maia On April 5, 2014 @ 11:31

why when i write my HTML code it dose not appear?

img src=”file:/’, pic, ‘”

#34 Comment By Yair Altman On April 5, 2014 @ 11:34

You cannot post direct HTML code in comments here.

re your question, as long as you update any uitable cell with valid HTML string it should work. If you would like my help to solve your specific issue, please contact me by email for personal consulting. You can find the link at the top-right of this page.

#35 Comment By Eike B. On May 8, 2014 @ 06:07

Hi Yair,

I’m using your createTable to create a table within your uisplitpane. Resizing the figure works fine but when I use the spliter to change the size of the panel the table is not resized. Is there something I’m missing here?

Best regards

Eike

#36 Comment By Yair Altman On May 8, 2014 @ 06:12

perhaps you didn’t make the table’s container have normalized units, or maybe you didn’t place it in the uisplitpane panel.

#37 Comment By Eike B. On May 8, 2014 @ 06:38

Thank you for you quick answer. All I do is:

 
f = figure();
[h1,h2,hDivider] = uisplitpane(f, 'Orientation', 'horizontal')
headers = {'Time', 'Object', 'Action', 'Progress', 'Test'};
data = [];
mTable = createTable(h2, headers, data, 'Buttons', 'off');

If i use:

mTable = createTable(h2, headers, data, 'Buttons', 'off', 'Units', 'normalized', 'position', [0 0 1 1]);

The table is spread over the whole figure so it seems that it is not placed in the panel.

#38 Comment By Daniel On May 13, 2014 @ 04:03

Hi Yair,
I’m using Matlab R2007b and can’t switch to a newer version due to my companies licence management 🙁 I wanna use your createTable function and need a callback like the CellEditCallback in the new uitable. In your book I can’t find something about it. Is there a way to implement a callback function that is called when a single call value has changed and that know which cell caused the callback (row & column)?

Thanks for your great work!
Daniel

#39 Comment By Yair Altman On May 13, 2014 @ 13:15

@Daniel – createTable uses the old (pre-R2008a) uitable, not the new version (which I personally dislike). This version uses DataChangedCallback rather than CellEditCallback, but the concept is similar – when the table data is changed, the callback is invoked.

See page 166 of my Matlab-Java book.

#40 Comment By Alejandro On July 14, 2014 @ 13:05

Yair, I just purchased the report; I cannot use the findjobj utility (see below). What is wrong?
Thank you

>> hfig1 = figure(1);
>> mtable = uitable(gcf,'Units','normalized','Position',pVec(1,:));
>> jscroll = findjobj(mtable);
Undefined function 'findjobj' for input arguments of type 'double'.
 
Did you mean:
>> jscroll = findobj(mtable);
>> jscroll = findobj(mtable)
jscroll =
    0.0094

#41 Comment By Yair Altman On July 14, 2014 @ 13:09

@Alejandro – you need to download the findjobj utility from the [12].

#42 Comment By Alex On August 4, 2014 @ 09:09

Hi Yair,

I’m working with a uitable that I would like to load with a defined rowwidth so that it can display multiple lines in a single cell. I’ve been able to play with the java object to allow dragging resizing of the row height, and I have been able to modify the RowHeights object. However, when I try to automate this, I find that the uitable won’t update with the defined rowheights until I click into it. Also, the scrollbar window doesn’t resize to fit the resized table.

I’ve purchased and been referring to your Undocumented Secrets book, but I don’t see anything in there about this issue. I read [13] that you said the only way to do this is by trapping the resizing callback, though I don’t know how to go about doing so. Could you please point me in the right direction?

Thank you for your time,
Alex

#43 Comment By Yair Altman On August 4, 2014 @ 09:44

@Alex – try to call the table’s repaint() method after updating it. If you need more detailed assistance, contact me by email for a short consulting session.

#44 Comment By Kathi On September 9, 2014 @ 05:59

Dear Yair,

I have a table and I’d like to make it’s column headers editable. I also found out about
com.jidesoft.grid.EditableTableHeader. But somehow I just can’t figure out how to use it.
I tried the following:

 
jScroll = findjobj(handles.uitable1);
jTable = jScroll.getViewport.getView;
import javax.swing.table.JTableHeader;
columnModel = jTable.getColumnModel();
jTable.setTableHeader(EditableHeader(columnModel));

But unfortunately this did not work. Additionally, The description of EditableHeader says the following:

public class EditableTableHeader
extends SortableTableHeader
implements CellEditorListener

As the name indicates, EditableTableHeader is an editable JTableHeader. Here is the code to use EditableTableHeader.

JTable table = new JTable(tableModel);
EditableTableHeader header = new EditableTableHeader(table.getColumnModel());
table.setTableHeader(header);

Once EditableTableHeader is installed on the table, user can double click on the table header to start editing. Pressing ENTER will commit editing or pressing ESCAPE to cancel editing.

By default, we will use TextFieldCellEditor as the cell editor. You can either override createDefaultEditor() method or call setDefaultEditor(javax.swing.table.TableCellEditor) to set your own cell editor. Please note, if you use your own cell editor, you may need to register ENTER and ESCAPE key to allow stop or cancel cell editing.

By default, all table columns will be editable. The same cell editor will be used for all columns. If you want only some of the columns editable and each one has its own cell editor, you just need to implement EditableColumnTableModel interface in your table model. EditableColumnTableModel has methods to let you decide which column is editable and what cell editor to be used.

However, I want the rows and columns of my table to not be editable. I only want to edit the headers.

I really hope that you can help me.
Thank you very much,
Kathi

#45 Comment By Kathi On September 9, 2014 @ 06:05

Here is the error I get:

 
Undefined function 'EditableHeader' for input arguments of type 'javax.swing.table.DefaultTableColumnModel'.

Error in table_bsp>table_bsp_OutputFcn (line 76)
  jTable.setTableHeader(EditableHeader(columnModel));

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

Error in table_bsp (line 42)
    gui_mainfcn(gui_State, varargin{:});

Best regards,
Kathi

#46 Comment By Yair Altman On September 9, 2014 @ 16:08

@Kathi – you made a typo in the class name and also forgot to mention the package name:

jTable.setTableHeader(com.jidesoft.grid.EditableTableHeader(columnModel));

This works for me.

#47 Comment By Kathi On September 10, 2014 @ 06:36

Dear Yair,
It’s works fine. Thank you very much! I just started to use Java and did not know how to include the package name :/
I’m really sorry, but may I ask you two more things?

I have a problem with my Callback to the jTable. I’m working with GUIDE and my opening-function looks like this:

% --- Executes just before Datenpunkte is made visible.
function Datenpunkte_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to Datenpunkte (see VARARGIN)
  
  % Choose default command line output for Datenpunkte
  handles.output = hObject;
  
  % Übergabeparameter auslesen
  handles.DB = varargin{end};
  
  % Update handles structure
  guidata(hObject, handles);


% UIWAIT makes Datenpunkte wait for user response (see UIRESUME)
% uiwait(handles.datenpunkte);

My output-function:

% --- Outputs from this function are returned to the command line.
function varargout = Datenpunkte_OutputFcn(hObject, eventdata, handles) 
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;

  jScroll = findjobj(handles.punkte_table);
  jTable = jScroll.getViewport.getView;

  jTable.setNonContiguousCellSelection(false);
  jTable.setColumnSelectionAllowed(false);
  jTable.setRowSelectionAllowed(true);

  import javax.swing.ListSelectionModel;
  selectPolicy = ListSelectionModel.SINGLE_SELECTION;
  jTable.setSelectionMode(selectPolicy);

  jTable = handle(jTable, 'CallbackProperties');
  set(jTable, 'MousePressedCallback', {@punkte_table_CellSelectionCallback, handles});

%   JAVA BUG - Data wird nicht upgedated
%   jTable = jScroll.getViewport.getComponent(0);
%   jTable.setSortable(1);

DB contains some Information about datapoints. The table contains the names of the datapoint. If you select one row in the table, the additional information which is saved in DB will be displayed in my GUI. Now you can change the datapoint information (such as Name etc.) if you want to. The changed information will be stored in DB_new. I also update the table afterwards. I update handles like this:

handles.db = db_new;
guidata(handles.figure1, handles)

I debugged everything and handles.db does now contain the new values. But if I select the row again, the old information will be displayed. It seems that every function except my punkte_table_CellSelectionCallback works with the changed handles struct. Do you have any idea why?

My second question is about sorting the table. Is there a way to catch the permutation of the rows? Because data is not updated after sorting.

Thank you for your time,
Kathi

#48 Comment By Yair Altman On September 10, 2014 @ 06:46

Kathi – this is beyond the time that I can spend pro-bono on questions here. If you need additional assistance please contact me by email for paid consulting.

#49 Comment By David On December 15, 2014 @ 18:21

Hi Yair, thank you for all the usefull information you have provided over the years. I have been playing around with making nice tables, and I am very interested in merging cells to create the appearance of merged headers. I know how to get the jTable and Span model, but when I check if isCellSpanOn() I always get false. Any advice for how I can turn this on? I am not looking to do anything too fancy, just merge the header of two columns so that I can display two different versions of the same information. Any help would be greatly appreciated.
All the best, David

#50 Comment By David On December 15, 2014 @ 19:16

Hi Yair,

I just sent a previous message about merging cells in a uitable, but I finally figured it out thanks to your book. What I am still having trouble with is removing the headers of the tables after this process. Any advice would be greatly appreciated. I tried turning them off the way I would normally in a table, but this doesn’t seem to work.

-David

#51 Comment By Niko On January 8, 2015 @ 12:26

Hi Yair,

I’m following your instructions in your book about overriding uitable with a CellSpanTable. One problem I’m facing now is that I don’t have a reliable way to modify the contents of row headers of the table. The MATLAB style

 
set(MyTable,'RowName',rowname);

seems to work sometimes but not always (it simply won’t update the row headers), and I haven’t figured out why yet.
Is there a way to modify the row headers on Java level, possibly similar to modifying the main data (using setValueAt to change specific entries, or a constructor to start all over)?
I’m using MATLAB version R2014b.
Thank you very much!

Niko

#52 Comment By Yair Altman On January 8, 2015 @ 12:42

@Niko – I believe that the row headers are implemented as a separate table. See page 159 in the book. You could access this table using a combination of getComponent() and getParent() and then use setValueAt() to modify its data. However, don’t be surprised if this gets overridden by Matlab when it decides to refresh the uitable…

#53 Comment By Meera On January 20, 2015 @ 08:04

Thanks! Changing the color background was really helpful. I was wondering if you knew how to include a symbols in uitables. I am trying to make a scroll down legend, and thought it be good to create a uitable, with one column the string and the second column the facecolor. It works well for my bar graphs, but then for my line graphs it gets confusing. Would you know how to get circles/star, triangles into a uitable?

#54 Comment By Meera On January 20, 2015 @ 10:47

Thanks! I am creating a legend using a uitable. Is there a way to get the marker and line in the uitable? I understand how to get the cell background to be the color that I want, but don’t know how to get the shapes in there.

#55 Comment By Yair Altman On January 21, 2015 @ 07:35

@Meera – you can use plain [14] for this, by placing the HTML code inside the relevant table cell’s string.

For example, ‘<html><b><font color=”red”>–&nabla;–‘ will generate –∇–

#56 Comment By Ahmed On March 27, 2015 @ 01:09

I am working on matlab R2013a
I tried to run this code but showing error

table = uitable(gcf,magic(10), {‘Name’ , ‘Level’, ‘Volum’,’jjjj’,’ggg’,’Ndsame’ , ‘Levdfel’, ‘Voldum’,’jfjj’,’ggfg’ });
javax.swing.Jtable
jscroll = findjobj(table);
jtable = jscroll.getViewport.getView;
jtable.setModel(javax.swing.table.DefaultTableModel(data,cols))

Warning: It appears you are using an obsolete version of uitable.
See the documentation for correct uitable usage:
help uitable and doc uitable

For more information, click here

> In uitable at 47
In Untitled2 at 1
Undefined function ‘findjobj’ for input arguments of type
‘javahandle_withcallbacks.com.mathworks.hg.peer.UitablePeer’.

Error in Untitled2 (line 2)
jscroll = findjobj(table);
jtable.getColumnModel.getColumn(2).setCellRenderer(ColorCellRenderer);
jtable.getColumnModel.getColumn(2).setCellEditor(ColorCellEditor);

any help will be appreciated

#57 Comment By Yair Altman On March 27, 2015 @ 01:14

@Ahmed – if you [15] I am sure that everything will become clear to you.

#58 Comment By C. Chu On April 10, 2015 @ 09:31

Hi Yair –

I can do setValueAt() against a cell to set its value, but how do I clear it? Passing in [] yields a NullPointerException, and putting in just a single space doesn’t do anything. Thanks!

#59 Comment By Yair Altman On April 11, 2015 @ 11:06

@Clayton – it depends on the uitable version (old/new), but in general entering spaces (string) is a good solution; you might also try {[]} but this has a good chance of failing.

#60 Comment By Ravi Goyal On December 10, 2015 @ 04:49

Dear Yair,

I have a question concerning numerial sorting in a uitable. We own your first book, however I cant find a reference how to sort a jtable numerically. The only hint i I see is on page 172 with the TableFilter Package which I cant get to work though.
Is there a JIDE setting to turn on or a built in class to use not just alphanumerical but real numerical sorting and would this specific topic be answered in your report or havent I just overlooked it in your book.

Thanks a lot
Best regards
Ravi G

#61 Comment By Yair Altman On December 10, 2015 @ 10:29

@Ravi – My uitable customization report (the topic of this post) is an expanded version of my book section on uitable, and refers to this problem. The problem stems from the fact that Matlab’s underlying data model class used by uitable reports all the table contents as lexical (i.e. sorted alphabetically) rather than numeric, even for numeric/logical values. The table sorter uses this information to determine whether to use numeric or lexical sorting, and therefore decides to always use lexical sorting. This is a definite bug in Matlab’s internal code (their data-model class), which has never been fixed (as far as I know, to this day).

There are two workarounds:

1. convert your numeric values into space-padded strings, thereby making lexical sorting behave as expected (this is explained in some more detail my uitable report)
2. replace the underlying data model with a new data model class that fixes the above-mentioned bug (this is not explained in my customization report). Email me if you wish to purchase such a class.

#62 Comment By AJITH KUMAR NARAYANASETTY On June 9, 2016 @ 09:07

when I try to use the uitable. A warning pops out saying that you are using an obsolete version.what should i do?

#63 Comment By Yair Altman On June 9, 2016 @ 09:17

Nothing – it’s a harmless warning. There are 2 versions of uitable and it simply tells you that you are using the older version, which is actually much better than the new one.

#64 Comment By Adam Gogacz On June 2, 2017 @ 15:21

Yair, is this report and the solutions therein still applicable on 2017a?

#65 Comment By Yair Altman On June 2, 2017 @ 15:30

yes they are

#66 Comment By Adam Gogacz On June 2, 2017 @ 15:41

Thanks

#67 Comment By John Miller On June 28, 2017 @ 15:36

Hi Yair,

I bought your report a couple of days ago and I am so pleased that I did. It has doubtless saved me many hours of frustration. I’ve developed many GUI-based apps but never in MATLAB so I’m sure you can understand why it and I don’t seem to get along very well 🙂

The knowledge you share in your report and also freely online is remarkable. I recommend the report to anyone who needs to do anything beyond the basic uitable functionality, no matter how mundane.

My need should have been straightforward to achieve but I knew otherwise. All I wanted was a non-editable, sortable table in which a user could double-click a row (and only one) to open a file specified in one of the columns. Trivial? Six hours says not but the report surely saved me that much time again.

Thank you very much!

John.

#68 Comment By Michele On February 6, 2019 @ 18:57

Dear Yair,

I would like to be able to enable/disable editing of specific cells in my table (not just the whole column!), and perhaps also grey-out the disabled cells.
Does your report cover this topic? And if not, do you have any suggestions on how to achieve this? (Possibly understandable also by a non-Java programmer!)

And as usual, thanks for the outstanding work!

#69 Comment By Mohammad On March 24, 2019 @ 03:39

Hey Yair,
I bought your book and my question is about set cells of table editable.
Changing “ColumnEditable” in matlab uitable is easy. Also if we use from java shape of matlab table, we can change column editable as “jtable.getModel.setColumnEditable(true)”.
But if we use from JIDE grids this will not works. How i can make all/one column editable in Java JTable/SortableTable?
Thanks a lot.

#70 Comment By Yair Altman On March 27, 2019 @ 00:08

@Mohammad – you can install a dummy column CellEditor, as follows:

% Disable editing but enable cell-selection for column #0
ce = javax.swing.DefaultCellEditor(javax.swing.JTextField);
ce.setClickCountToStart(intmax);  % =never...
jTable.getColumnModel.getColumn(0).setCellEditor(ce);

This technique is an example of the additional tips that are included in my uitable report and not in the book (the report is an expanded version of the book’s uitable section).

#71 Comment By Nivetha On March 28, 2019 @ 05:53

Hi Yair,

The uitable is getting sorted like 1,10,11,2,22,3,33 instead of 1,2,3….. in R2016b version.

Any fix for this?

#72 Comment By Yair Altman On March 29, 2019 @ 16:31

@Nivetha – I discuss the issue of uitable sorting in my uitable report.

#73 Comment By Reza On April 12, 2019 @ 04:21

The reason is that matlab look to every field as text value.
I think you must use from main Java table… “com.jidesoft.grid.SortableTable”

#74 Comment By Luis Santiago On June 10, 2021 @ 17:05

Hi Yair.
Your articles are excellent and, even now, they are still applicable. Is the uitable report still available?
I’d really like getting it.

#75 Comment By Yair Altman On June 10, 2021 @ 18:33

Yes, the report is still available. You can [16].

#76 Comment By Santiago On July 21, 2022 @ 21:38

Hi Yair.
I’m using the MouseReleasedCallback but I need to get the indices of the selected cell. I can get them without problems with left clicks but, if I try to do it with a right click the selectedrow and selectedcolumn show the last selected cell (with a left click). is there a way to get the newly selected cell (with a right click)?
thanks in advanced,

#77 Comment By Yair Altman On July 22, 2022 @ 13:19

Santiago – you can get the mouse X,Y positions from the Java eventData object (getX(), getY()), convert this into a point (p=java.awt.Point(x,y)), then use the JTable methods rowAtPoint(p), columnAtPoint(p) to get the corresponding Java row/column indices. It gets a bit trickier when you use table wrappers (e.g. for sorting/filtering) but it’s the same basic idea.

#78 Comment By Santiago On July 22, 2022 @ 18:43

It works perfectly.
Thanks so much.

#79 Comment By Kei On April 25, 2023 @ 08:37

Hello Yair
Thank you for this great article.
I would like to freeze first two columns in uitable. Do you know if such option is available?
Since looks like this option is not available as a default, I tried to create two uitables, one is for the headers I want to freeze and other is for the data. However, I ran into another issue that I need to syncronize scroll bars of two uitables, that is not supported as default too.
Thank you!

#80 Comment By Yair Altman On April 25, 2023 @ 11:12

Kei – this is possible, I believe that I saw this ability somewhere, a few years ago. I don’t remember exactly where, it will require a bit of research, but I’m pretty sure that this is possible.
Contact me offline (altmany at gmail) if you wish me to spend some time to look this up for you.


Article printed from Undocumented Matlab: https://undocumentedmatlab.com

URL to article: https://undocumentedmatlab.com/articles/uitable-customization-report

URLs in this post:

[1] uitable sorting: http://undocumentedmatlab.com/blog/uitable-sorting/

[2] get my uitable report: https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&business=altmany@gmail.com&currency_code=USD&amount=29&return=&item_name=Matlab-uitable-report

[3] MATLAB Performance Tuning: https://undocumentedmatlab.com/books/matlab-performance

[4] Uitable sorting : https://undocumentedmatlab.com/articles/uitable-sorting

[5] Uitable cell colors : https://undocumentedmatlab.com/articles/uitable-cell-colors

[6] treeTable : https://undocumentedmatlab.com/articles/treetable

[7] Matlab toolstrip – part 3 (basic customization) : https://undocumentedmatlab.com/articles/matlab-toolstrip-part-3-basic-customization

[8] Multi-line uitable column headers : https://undocumentedmatlab.com/articles/multi-line-uitable-column-headers

[9] GUIDE customization : https://undocumentedmatlab.com/articles/guide-customization

[10] : https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&business=octahedron.ltd@gmail.com&currency_code=USD&amount=35&return=&item_name=Matlab-uitable-report

[11] : https://undocumentedmatlab.com/blog/images-in-matlab-uicontrols-and-labels

[12] : http://www.mathworks.com/matlabcentral/fileexchange/14317-findjobj-find-java-handles-of-matlab-graphic-objects

[13] : https://www.mathworks.com/matlabcentral/newsreader/view_thread/289838

[14] : http://www.w3schools.com/HTML/html_symbols.asp

[15] : https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&business=altmany@gmail.com&currency_code=USD&amount=35&return=&item_name=Matlab-uitable-report

[16] : https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&business=altmany@gmail.com&currency_code=USD&amount=29&return=&item_name=Matlab-uitable-report

Copyright © Yair Altman - Undocumented Matlab. All rights reserved.