Uitable customization report

In last week’s report about uitable sorting, I offered a report that I have written which covers uitable customization in detail. Several people have asked for more details about the contents of this report. This is a reasonable request, and so in today’s post I will discuss in a bit more detail the highlights of what can be achieved to customize Matlab uitables. For the fine details, well, get my uitable report (45 pages PDF, $25).

1. Introduction

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

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

2. Customizing uitable

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

annotated uitable sub-components

annotated uitable sub-components

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

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

uitable with HTML cell contents and tooltip

uitable with HTML cell contents and tooltip


uitable with cell images

uitable with cell images

3. Cell renderers and cell editors

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


uitable with a non-standard cell-renderer

uitable with a non-standard cell-renderer


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

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


uitable with custom CellRenderer and CellEditor

uitable with custom CellRenderer and CellEditor

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

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

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


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

4. Table callbacks

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

5. Customizing scrollbars, column widths and selection behavior

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

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

6. Data sorting

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

Multi-column sorting with blue sort-order numbers

Multi-column sorting with blue sort-order numbers

7. Data filtering

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

uitable data filtering

uitable data filtering

8. JIDE customizations

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

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

Resizing columns

Resizing columns

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

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

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

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

Custom header-row context-menu

Custom header-row context-menu

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

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

10. Run-time performance

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

11. Final remarks

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

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

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

Appendix – JIDE Grids

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

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

Date selection comb-box

Date selection combo-box

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

TreeTable example

TreeTable example

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

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

IP address and credit-card entry boxes

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

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

Tags: , , , , , , , ,

Bookmark and SharePrint Print

74 Responses to Uitable customization report

  1. S says:

    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. Marcel says:

    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

    • @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 says:

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

    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

  5. Matthias says:

    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

    • @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 says:

    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.

  7. Matthew says:

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

    • @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 says:

    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.

  9. Shad says:

    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?

  10. Pingback: Real-time trading system demo | Undocumented Matlab

  11. Ramiro Massol says:

    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

    • You can set up a KeyPressedCallback on the JTable

    • ramiro massol says:

      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. Pingback: treeTable | Undocumented Matlab

  13. Kevin Joosten says:

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

      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. Pingback: Rich-contents log panel | Undocumented Matlab

  15. Pingback: Editbox data input validation | Undocumented Matlab

  16. Sjors Teeuwen says:

    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

  17. Jacques says:

    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);
  18. maia says:

    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?

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

    • maia says:

      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 .

    • maia says:

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

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

    • 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. says:

    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

    • 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. says:

      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.

  20. Daniel says:

    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

    • @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 says:

    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
  22. Alex says:

    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

    • @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 says:

    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

    • Kathi says:

      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

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

    • Kathi says:

      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

    • 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 says:

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

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

    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

    • @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 says:

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

      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.

    • @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 says:

    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

  28. C. Chu says:

    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!

    • @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 says:

    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

    • @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 says:

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

    • 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 says:

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

  32. Adam Gogacz says:

    Thanks

  33. 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 says:

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

    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.

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

  36. Nivetha says:

    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?

Leave a Reply

Your email address will not be published. Required fields are marked *