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 customization report

August 3, 2011 81 Comments

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, $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. 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“.

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.

Related posts:

  1. Uitable sorting – Matlab's uitables can be sortable using simple undocumented features...
  2. Uitable cell colors – A few Java-based customizations can transform a plain-looking data table into a lively colored one. ...
  3. treeTable – A description of a sortable, groupable tree-table control that can be used in Matlab is provided. ...
  4. Matlab toolstrip – part 3 (basic customization) – Matlab toolstrips can be created and customized in a variety of ways. ...
  5. Multi-line uitable column headers – Matlab uitables can present long column headers in multiple lines, for improved readability. ...
  6. GUIDE customization – Matlab's GUI Design Editor (GUIDE) has several interesting undocumented features. This post describes how to customize GUIDE rulers....
GUI HTML Internal component Java JIDE uitable uitable report uitools Undocumented feature
Print Print
« Previous
Next »
81 Responses
  1. S August 9, 2011 at 02:47 Reply

    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!

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

      @Simon – uitable header row and header column customizations are explored in detail in my uitable report

  2. Marcel August 24, 2011 at 23:24 Reply

    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

    • Yair Altman August 25, 2011 at 00:24 Reply

      @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).

  3. Eero Kuusi September 1, 2011 at 07:31 Reply

    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.

  4. quant October 21, 2011 at 07:44 Reply

    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

    • Yair Altman October 22, 2011 at 09:57 Reply

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

  5. Matthias January 31, 2012 at 16:10 Reply

    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

    • Yair Altman January 31, 2012 at 16:57 Reply

      @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.

  6. Harold February 15, 2012 at 00:25 Reply

    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.

    • Yair Altman February 25, 2012 at 15:44 Reply

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

  7. Matthew November 9, 2012 at 06:52 Reply

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

    • Yair Altman November 18, 2012 at 13:39 Reply

      @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.

  8. Marco Santos March 22, 2013 at 05:24 Reply

    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.

    • Yair Altman March 22, 2013 at 05:57 Reply

      @Marco – try this:

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

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

  9. Shad April 5, 2013 at 08:15 Reply

    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?

    • Yair Altman April 5, 2013 at 08:27 Reply

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

  10. Real-time trading system demo | Undocumented Matlab May 29, 2013 at 06:18 Reply

    […] Customized data table […]

  11. Ramiro Massol July 2, 2013 at 07:03 Reply

    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

    • Yair Altman July 3, 2013 at 15:18 Reply

      You can set up a KeyPressedCallback on the JTable

      • ramiro massol July 7, 2013 at 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

  12. treeTable | Undocumented Matlab August 6, 2013 at 01:08 Reply

    […] 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. […]

  13. Kevin Joosten September 3, 2013 at 01:00 Reply

    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

    • Kevin Joosten September 5, 2013 at 03:28 Reply

      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

  14. Rich-contents log panel | Undocumented Matlab September 20, 2013 at 01:57 Reply

    […] Customized data table […]

  15. Editbox data input validation | Undocumented Matlab October 2, 2013 at 10:12 Reply

    […] (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 […]

  16. Sjors Teeuwen October 25, 2013 at 06:58 Reply

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

    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

  17. Jacques March 5, 2014 at 10:09 Reply

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

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

    • Yair Altman March 5, 2014 at 10:43 Reply

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

  18. maia April 3, 2014 at 14:15 Reply

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

    [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?

    • Yair Altman April 3, 2014 at 15:00 Reply

      @Maia – You’re probably not formatting your HTML image URL correctly. This is explained here: http://undocumentedmatlab.com/blog/images-in-matlab-uicontrols-and-labels

    • maia April 5, 2014 at 11:26 Reply

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

      [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 .

      • maia April 5, 2014 at 11:31

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

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

      • Yair Altman April 5, 2014 at 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.

  19. Eike B. May 8, 2014 at 06:07 Reply

    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

    • Yair Altman May 8, 2014 at 06:12 Reply

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

      • Eike B. May 8, 2014 at 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');

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

        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.

  20. Daniel May 13, 2014 at 04:03 Reply

    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

    • Yair Altman May 13, 2014 at 13:15 Reply

      @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.

  21. Alejandro July 14, 2014 at 13:05 Reply

    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

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

    • Yair Altman July 14, 2014 at 13:09 Reply

      @Alejandro – you need to download the findjobj utility from the Matlab File Exchange.

  22. Alex August 4, 2014 at 09:09 Reply

    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 here 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

    • Yair Altman August 4, 2014 at 09:44 Reply

      @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.

  23. Kathi September 9, 2014 at 05:59 Reply

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

    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

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

    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

    • Kathi September 9, 2014 at 06:05 Reply

      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{:});

      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

      • Yair Altman September 9, 2014 at 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));

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

        This works for me.

      • Kathi September 10, 2014 at 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);

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

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

        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

      • Yair Altman September 10, 2014 at 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.

  24. David December 15, 2014 at 18:21 Reply

    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

    • David December 15, 2014 at 19:16 Reply

      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

  25. Niko January 8, 2015 at 12:26 Reply

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

    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

    • Yair Altman January 8, 2015 at 12:42 Reply

      @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…

  26. Meera January 20, 2015 at 08:04 Reply

    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?

    • Meera January 20, 2015 at 10:47 Reply

      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.

      • Yair Altman January 21, 2015 at 07:35

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

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

  27. Ahmed March 27, 2015 at 01:09 Reply

    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

    • Yair Altman March 27, 2015 at 01:14 Reply

      @Ahmed – if you purchase my uitable report I am sure that everything will become clear to you.

  28. C. Chu April 10, 2015 at 09:31 Reply

    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!

    • Yair Altman April 11, 2015 at 11:06 Reply

      @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.

  29. Ravi Goyal December 10, 2015 at 04:49 Reply

    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

    • Yair Altman December 10, 2015 at 10:29 Reply

      @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.

  30. AJITH KUMAR NARAYANASETTY June 9, 2016 at 09:07 Reply

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

    • Yair Altman June 9, 2016 at 09:17 Reply

      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.

  31. Adam Gogacz June 2, 2017 at 15:21 Reply

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

    • Yair Altman June 2, 2017 at 15:30 Reply

      yes they are

  32. Adam Gogacz June 2, 2017 at 15:41 Reply

    Thanks

  33. John Miller June 28, 2017 at 15:36 Reply

    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.

  34. Michele February 6, 2019 at 18:57 Reply

    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!

  35. Mohammad March 24, 2019 at 03:39 Reply

    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.

    • Yair Altman March 27, 2019 at 00:08 Reply

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

      % 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).

  36. Nivetha March 28, 2019 at 05:53 Reply

    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?

    • Yair Altman March 29, 2019 at 16:31 Reply

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

    • Reza April 12, 2019 at 04:21 Reply

      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”

  37. Luis Santiago June 10, 2021 at 17:05 Reply

    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.

    • Yair Altman June 10, 2021 at 18:33 Reply

      Yes, the report is still available. You can get it here.

  38. Santiago July 21, 2022 at 21:38 Reply

    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,

    • Yair Altman July 22, 2022 at 13:19 Reply

      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.

      • Santiago July 22, 2022 at 18:43

        It works perfectly.
        Thanks so much.

  39. Kei April 25, 2023 at 08:37 Reply

    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!

    • Yair Altman April 25, 2023 at 11:12 Reply

      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.

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
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) uitable (6) uitools (20) Undocumented feature (187) Undocumented function (37) Undocumented property (20)
Recent Comments
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