Home > m > gui > ltpdaRepoGUI > createTable.m

createTable

PURPOSE ^

createTable - create nice-looking table based on javax.swing.JTable

SYNOPSIS ^

function [mtable, buttons] = createTable(pnContainer,headers,data,buttonsFlag,varargin)

DESCRIPTION ^

 createTable - create nice-looking table based on javax.swing.JTable

 Syntax:
    [mtable, buttons] = createTable (pnContainer, headers, data, buttonsFlag, 'PropName',PropValue, ...)

 Input Parameters:
    pnContainer - optional handle to container uipanel or figure. If empty/unsupplied then current figure will be used
    headers     - optional cell array of column header strings. If unsupplied then = {'A','B','C'}
    data        - optional vector/matrix (either scalar or cell array) of data values
    buttonsFlag - optional flag indicating whether to create the table-manipulation buttons. Default = true
    'PropName',PropValue - 
                  optional list of property pairs (e.g., 'AutoResizeMode',4,'Editable',false,'Position',[.1,.1,.5,.5])
                  Note: PropName must be either an mtable property ('Visible','Editable','Position','Units',
                        'DataChangedCallback',...) or otherwise a Javax.swing.JTable property ('ShowGrid','Name',...).
                        Abbreviated PropNames are unsupported for mtable properties (which are few) - only for JTable

 Output parameters:
    mtable      - handle to mtable object (a Matlab object)
    buttons     - handles to table manipulation buttons: [<appendRow> <insertRow> <deleteRow> <deleteAll> <printAll>]

 Examples:
    [mtable, buttons] = createTable;
    [mtable, buttons] = createTable(gcf,'column name');
    mtable = createTable([],{'a','b','c','d'},{false,1.3,uint16(45),'ert'; true,pi,uint16(-4),'defrgt'})
    mtable = createTable([],{'a','b','c','d'},magic(4),false,'AutoResizeMode',javax.swing.JTable.AUTO_RESIZE_ALL_COLUMNS)
    mtable = createTable([],{'rads','sin','cos'},[pi,sin(pi),cos(pi)],'SelectionMode',javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION)

 Usage:
    The table automatically resizes to fill the pnContainer (you may modify this via the 'Position' property).
    The table automatically sets the columns' cell editor and renderer based on the supplied data. Logical values are
       given a checkbox, strings are left-aligned (numbers are right-aligned). You can always override the defaults.
    You can change column widths by dragging the column borders on the header row.
    You can sort columns by clicking the column header (once to sort descending, once again to sort ascending and once
       more for the unsorted view). Sorting multiple columns is done by control-clicking all relevant columns (the
       sorting icon is decreased in size for each additional minor sort col).
    You can copy/paste any consecutive region of table cells, just as in Excel. You can select entire rows or columns
       by right-clicking their header. You can also paste Excel data directly, with Ctrl-Shift-V (or use the context
       menu by right-clicking) at the target table cell.
    For additional tips about how to set multiple aspects of the table, refer to:
       <a href="http://java.sun.com/docs/books/tutorial/uiswing/components/table.html">http://java.sun.com/docs/books/tutorial/uiswing/components/table.html</a>

 Programming tips/cues/examples:
    mtable = creatTable(...)
    jtable = mtable.getTable;
    mtable.setVisible(false);
    mtable.setCheckBoxEditor(1);  % Set first column to a checkbox (see Note 2 below)
    cb = javax.swing.JComboBox({'First','Last'}); cb.setEditable(true);  % prepare an editable drop-down CellEditor
    editor = javax.swing.DefaultCellEditor(cb);
    jtable.getColumnModel.getColumn(1).setCellEditor(editor);  % assign this editor to second column (see Note 2)
    jtable.getColumnModel.getColumn(0).setMaxWidth(20);  % Limit width of first (checkbox) column (see Note 2)
    mtable.setEditable(0,false);  % Disable editing first column (see note 2 below)
    renderer = javax.swing.table.DefaultTableCellRenderer;  % or: renderer = jtable.getColumnModel.getColumn(1).getCellRenderer
    renderer.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);  % useful for numbers rendered as strings e.g.: jtable.setValueAt(sprintf('%.1f',pi,rowIdx,colIdx))
    jtable.getColumnModel.getColumn(1).setCellRenderer(renderer);  % right-align second column (see note 2)
    data = cell(mtable.getData);  % a cell matrix (mtable.getData is a java.lang.Object[][] object, using base-1 indexing)
    data = mtable.getTableModel.getDataVector;  % a java.util.Vector object ([[false, 1.3, 45, ert], [true, 3.14,...]])
    jtable.setValueAt(value,rowIdx,colIdx);  % 0-based Idx - see Note 2 below
    jtable.getModel.addRow({true, pi, int16(45), 'test'});  % appends a row to the bottom of the table
    mtable.DataChangedCallback = [];  % used to temporarily disable data-change callbacks
    mtable.DataChangedCallback = @myDataChange_Callback;  % myDataChange_Callback is a Matlab function

    % Sample dataChange_Callback function
    function dataChange_Callback(mtable, eventdata)
       if ~ishandle(mtable),  return;  end
          % Prevent re-entry here if the callback is not thread-safe - see Note 3 below
       eventDetails = eventdata.getEvent;
       modifiedColIdx = eventDetails.getColumn;
       modifiedRowIdx = eventDetails.getFirstRow;
       if modifiedColIdx>=0 && modifiedRowIdx>=0
          data = mtable.getData;
          newValue = data(modifiedRowIdx+1,modifiedColIdx+1);  % see Note 2 below
          switch modifiedColIdx
            case ...
          end
       end

 Notes:
    1. Some (very few) JTable features are inconsistent or unavailable in different jave versions. Type 
       '<a href="matlab:version -java">version -java</a>' at the command prompt to see your specific java version.
    2. Note that java uses 0-based indexing, while Matlab is 1-based. The returned mtable parameter is a Matlab object
       (so use 1-base), while mtable.getXXX returns java objects (0-based). jtable above is an example of a java object.
    3. Modifying mtable.DataChangedCallback within the callback doesn't work - you need to use some global flag/mutex
    4. The <Print> button uses Excel to parse and print the table
    5. Due to Matlab limitations (specifically, of uitable/UitablePeer) the table is created as a direct child of
       the container figure (although it is visually positioned within pnContainer)
    6. To enable sorting functionality, the attached TableSorter.jar file must be located in the java classpath.
       See the Matlab documentation for <a href="matlab:doc javaclasspath">javaclasspath</a>. Note that using 
       javaaddpath(...) to set the path has a nasty side-effect (at least since Matlab 7.2) of clearing all globals!
       An alternative is to place the pathname for TableSorter.jar in the <a href="matlab:which classpath.txt">classpath.txt</a> file

 Known issues/limitations:
    - Column alignment not preserved during Print
    - Print fails if Excel unavailable (maybe directly print tab-separated text data)
    - Unable to add/delete rows or to print via context menu (right-click)
    - Table is created as a direct child of figure, not pnContainer (see Note 5 above)

 Bugs and suggestions:
    Please send to Yair Altman (altmany at gmail dot com)

 See also:
    uitable, java, javaclasspath

 Release history:
    1.0 2007-03-09: initial version
    1.1 2007-03-22: fixed selected row# on deletion of bottom row, main comment, missing option; added header tooltip


 25-02-08 Adapted and imported into LTPDA
    M Hewitson

 $Id: createTable.m,v 1.2 2008/03/01 11:46:46 hewitson Exp $

CROSS-REFERENCE INFORMATION ^

This function calls: This function is called by:

SUBFUNCTIONS ^

SOURCE CODE ^

0001 function [mtable, buttons] = createTable(pnContainer,headers,data,buttonsFlag,varargin)
0002 % createTable - create nice-looking table based on javax.swing.JTable
0003 %
0004 % Syntax:
0005 %    [mtable, buttons] = createTable (pnContainer, headers, data, buttonsFlag, 'PropName',PropValue, ...)
0006 %
0007 % Input Parameters:
0008 %    pnContainer - optional handle to container uipanel or figure. If empty/unsupplied then current figure will be used
0009 %    headers     - optional cell array of column header strings. If unsupplied then = {'A','B','C'}
0010 %    data        - optional vector/matrix (either scalar or cell array) of data values
0011 %    buttonsFlag - optional flag indicating whether to create the table-manipulation buttons. Default = true
0012 %    'PropName',PropValue -
0013 %                  optional list of property pairs (e.g., 'AutoResizeMode',4,'Editable',false,'Position',[.1,.1,.5,.5])
0014 %                  Note: PropName must be either an mtable property ('Visible','Editable','Position','Units',
0015 %                        'DataChangedCallback',...) or otherwise a Javax.swing.JTable property ('ShowGrid','Name',...).
0016 %                        Abbreviated PropNames are unsupported for mtable properties (which are few) - only for JTable
0017 %
0018 % Output parameters:
0019 %    mtable      - handle to mtable object (a Matlab object)
0020 %    buttons     - handles to table manipulation buttons: [<appendRow> <insertRow> <deleteRow> <deleteAll> <printAll>]
0021 %
0022 % Examples:
0023 %    [mtable, buttons] = createTable;
0024 %    [mtable, buttons] = createTable(gcf,'column name');
0025 %    mtable = createTable([],{'a','b','c','d'},{false,1.3,uint16(45),'ert'; true,pi,uint16(-4),'defrgt'})
0026 %    mtable = createTable([],{'a','b','c','d'},magic(4),false,'AutoResizeMode',javax.swing.JTable.AUTO_RESIZE_ALL_COLUMNS)
0027 %    mtable = createTable([],{'rads','sin','cos'},[pi,sin(pi),cos(pi)],'SelectionMode',javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION)
0028 %
0029 % Usage:
0030 %    The table automatically resizes to fill the pnContainer (you may modify this via the 'Position' property).
0031 %    The table automatically sets the columns' cell editor and renderer based on the supplied data. Logical values are
0032 %       given a checkbox, strings are left-aligned (numbers are right-aligned). You can always override the defaults.
0033 %    You can change column widths by dragging the column borders on the header row.
0034 %    You can sort columns by clicking the column header (once to sort descending, once again to sort ascending and once
0035 %       more for the unsorted view). Sorting multiple columns is done by control-clicking all relevant columns (the
0036 %       sorting icon is decreased in size for each additional minor sort col).
0037 %    You can copy/paste any consecutive region of table cells, just as in Excel. You can select entire rows or columns
0038 %       by right-clicking their header. You can also paste Excel data directly, with Ctrl-Shift-V (or use the context
0039 %       menu by right-clicking) at the target table cell.
0040 %    For additional tips about how to set multiple aspects of the table, refer to:
0041 %       <a href="http://java.sun.com/docs/books/tutorial/uiswing/components/table.html">http://java.sun.com/docs/books/tutorial/uiswing/components/table.html</a>
0042 %
0043 % Programming tips/cues/examples:
0044 %    mtable = creatTable(...)
0045 %    jtable = mtable.getTable;
0046 %    mtable.setVisible(false);
0047 %    mtable.setCheckBoxEditor(1);  % Set first column to a checkbox (see Note 2 below)
0048 %    cb = javax.swing.JComboBox({'First','Last'}); cb.setEditable(true);  % prepare an editable drop-down CellEditor
0049 %    editor = javax.swing.DefaultCellEditor(cb);
0050 %    jtable.getColumnModel.getColumn(1).setCellEditor(editor);  % assign this editor to second column (see Note 2)
0051 %    jtable.getColumnModel.getColumn(0).setMaxWidth(20);  % Limit width of first (checkbox) column (see Note 2)
0052 %    mtable.setEditable(0,false);  % Disable editing first column (see note 2 below)
0053 %    renderer = javax.swing.table.DefaultTableCellRenderer;  % or: renderer = jtable.getColumnModel.getColumn(1).getCellRenderer
0054 %    renderer.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);  % useful for numbers rendered as strings e.g.: jtable.setValueAt(sprintf('%.1f',pi,rowIdx,colIdx))
0055 %    jtable.getColumnModel.getColumn(1).setCellRenderer(renderer);  % right-align second column (see note 2)
0056 %    data = cell(mtable.getData);  % a cell matrix (mtable.getData is a java.lang.Object[][] object, using base-1 indexing)
0057 %    data = mtable.getTableModel.getDataVector;  % a java.util.Vector object ([[false, 1.3, 45, ert], [true, 3.14,...]])
0058 %    jtable.setValueAt(value,rowIdx,colIdx);  % 0-based Idx - see Note 2 below
0059 %    jtable.getModel.addRow({true, pi, int16(45), 'test'});  % appends a row to the bottom of the table
0060 %    mtable.DataChangedCallback = [];  % used to temporarily disable data-change callbacks
0061 %    mtable.DataChangedCallback = @myDataChange_Callback;  % myDataChange_Callback is a Matlab function
0062 %
0063 %    % Sample dataChange_Callback function
0064 %    function dataChange_Callback(mtable, eventdata)
0065 %       if ~ishandle(mtable),  return;  end
0066 %          % Prevent re-entry here if the callback is not thread-safe - see Note 3 below
0067 %       eventDetails = eventdata.getEvent;
0068 %       modifiedColIdx = eventDetails.getColumn;
0069 %       modifiedRowIdx = eventDetails.getFirstRow;
0070 %       if modifiedColIdx>=0 && modifiedRowIdx>=0
0071 %          data = mtable.getData;
0072 %          newValue = data(modifiedRowIdx+1,modifiedColIdx+1);  % see Note 2 below
0073 %          switch modifiedColIdx
0074 %            case ...
0075 %          end
0076 %       end
0077 %
0078 % Notes:
0079 %    1. Some (very few) JTable features are inconsistent or unavailable in different jave versions. Type
0080 %       '<a href="matlab:version -java">version -java</a>' at the command prompt to see your specific java version.
0081 %    2. Note that java uses 0-based indexing, while Matlab is 1-based. The returned mtable parameter is a Matlab object
0082 %       (so use 1-base), while mtable.getXXX returns java objects (0-based). jtable above is an example of a java object.
0083 %    3. Modifying mtable.DataChangedCallback within the callback doesn't work - you need to use some global flag/mutex
0084 %    4. The <Print> button uses Excel to parse and print the table
0085 %    5. Due to Matlab limitations (specifically, of uitable/UitablePeer) the table is created as a direct child of
0086 %       the container figure (although it is visually positioned within pnContainer)
0087 %    6. To enable sorting functionality, the attached TableSorter.jar file must be located in the java classpath.
0088 %       See the Matlab documentation for <a href="matlab:doc javaclasspath">javaclasspath</a>. Note that using
0089 %       javaaddpath(...) to set the path has a nasty side-effect (at least since Matlab 7.2) of clearing all globals!
0090 %       An alternative is to place the pathname for TableSorter.jar in the <a href="matlab:which classpath.txt">classpath.txt</a> file
0091 %
0092 % Known issues/limitations:
0093 %    - Column alignment not preserved during Print
0094 %    - Print fails if Excel unavailable (maybe directly print tab-separated text data)
0095 %    - Unable to add/delete rows or to print via context menu (right-click)
0096 %    - Table is created as a direct child of figure, not pnContainer (see Note 5 above)
0097 %
0098 % Bugs and suggestions:
0099 %    Please send to Yair Altman (altmany at gmail dot com)
0100 %
0101 % See also:
0102 %    uitable, java, javaclasspath
0103 %
0104 % Release history:
0105 %    1.0 2007-03-09: initial version
0106 %    1.1 2007-03-22: fixed selected row# on deletion of bottom row, main comment, missing option; added header tooltip
0107 %
0108 %
0109 % 25-02-08 Adapted and imported into LTPDA
0110 %    M Hewitson
0111 %
0112 % $Id: createTable.m,v 1.2 2008/03/01 11:46:46 hewitson Exp $
0113 %
0114 %
0115 
0116 % License to use and modify this code is granted freely to all interested, as long as the original author is
0117 % referenced and attributed as such. The original author maintains the right to be solely associated with this work.
0118 
0119 % Programmed and Copyright by Yair M. Altman: altmany(at)gmail.com
0120 % $Revision: 1.2 $  $Date: 2008/03/01 11:46:46 $
0121 
0122   %try
0123       % Ensure that java swing is enabled...
0124       if ~usejava('swing')
0125           error('createTable:NeedSwing','Java tables require Java Swing.');
0126       end
0127 
0128       % Create a panel spanning entire figure area, if panel handle was not supplied
0129       if (nargin < 1) || isempty(pnContainer) || ~ishandle(pnContainer)
0130           pnContainer = uipanel('parent',gcf,'tag','TablePanel');
0131       end
0132       pnContainerPos = getpixelposition(pnContainer,1);
0133       if isa(handle(pnContainer), 'figure')
0134           pnContainerPos(1:2) = 0;
0135       end
0136 
0137       % Get handle to parent figure
0138       hFig = ancestor(pnContainer,'figure');
0139 
0140       % Determine whether table manipulation buttons are requested
0141       if nargin < 4 || isempty(buttonsFlag) || ~(isnumeric(buttonsFlag) || islogical(buttonsFlag))
0142           if nargin >= 4,  varargin = {buttonsFlag, varargin{:}};  end
0143           buttonsFlag = true;
0144       end
0145       if buttonsFlag
0146           margins = [1,30,0,-30];  % With buttons
0147       else
0148           margins = [1,1,0,0];   % No buttons
0149       end
0150 
0151       % Get the uitable's required position within pnContainer
0152       tablePosition = pnContainerPos + margins;    % Relative to the figure
0153 
0154       % Set default header names, if not supplied
0155       if nargin < 2
0156           headers = {'A','B','C'};  % 3 columns by default
0157       elseif isempty(headers)
0158           headers = cell(1,size(data,2));
0159       elseif ischar(headers)
0160           headers = {headers};
0161       end
0162 
0163       % Start with dummy data, just so that uitable can be initialized (or use supplied data, if available)
0164       if nargin < 3 || isempty(data)
0165           numRows = 0;
0166           numCols = length(headers);
0167           data = zeros(1,numCols);
0168       else
0169           numRows = size(data,1);
0170           numCols = size(data,2);
0171       end
0172       % Convert to cell-format (if not so already)
0173       if ~iscell(data)
0174           data = mat2cell(data,ones(1,size(data,1)),ones(1,numCols));
0175       end
0176 
0177       % Create a sortable uitable within pnHandle
0178       mtable = uitable(hFig, 'position',tablePosition, 'Data',data, 'ColumnNames',headers);
0179       mtable.setNumRows(numRows);
0180       set(mtable,'units','normalized');  % this will resize the table whenever its container is resized
0181 
0182       % jtable is the underlying java JTable - access to lots more functionality...
0183       % Note: actually, jtable is a com.mathworks.hg.peer.UitablePeer$PeerSpreadsheetTable object, but this extends
0184       % ^^^^  javax.swing.JTable, so for all practical purposes you may use it as a JTable
0185       jtable = mtable.getTable;
0186 
0187       % Fix for JTable focus bug : see http://bugs.sun.com/bugdatabase/view_bug.do;:WuuT?bug_id=4709394
0188       % Taken from: http://xtargets.com/snippets/posts/show/37
0189       jtable.putClientProperty('terminateEditOnFocusLost', java.lang.Boolean.TRUE);
0190 
0191       % We want to use sorter, not data model...
0192       % unfortunately, UitablePeer expects DefaultTableModel (not TableSorter) so we need a modified UitablePeer class
0193       % however, UitablePeer is a Matlab class, so instead let's use a modified TableSorter and attach it to the Model
0194       %sorter = com.mathworks.toolbox.dasstudio.util.TableSorter;  % Failed attempt...
0195       %sorter = com.mathworks.mwswing.DefaultSortableTable;        % ...another failed attempt...
0196       if ~isempty(which('TableSorter'))
0197           % Add TableSorter as TableModel listener
0198           sorter = TableSorter(jtable.getModel());  %(table.getTableModel);
0199           %tablePeer = UitablePeer(sorter);  % This is not accepted by UitablePeer... - see comment above
0200           jtable.setModel(sorter);
0201           sorter.setTableHeader(jtable.getTableHeader());
0202 
0203           % Set the header tooltip (with sorting instructions)
0204           jtable.getTableHeader.setToolTipText('<html>&nbsp;<b>Click</b> to sort up; <b>Shift-click</b> to sort down<br>&nbsp;<b>Ctrl-click</b> (or <b>Ctrl-Shift-click</b>) to sort secondary&nbsp;<br>&nbsp;<b>Click again</b> to change sort direction<br>&nbsp;<b>Click a third time</b> to return to unsorted view<br>&nbsp;<b>Right-click</b> to select entire column</html>');
0205       else
0206           % Set the header tooltip (no sorting instructions...)
0207           jtable.getTableHeader.setToolTipText('<html>&nbsp;<b>Click</b> to select entire column<br>&nbsp;<b>Ctrl-click</b> (or <b>Shift-click</b>) to select multiple columns&nbsp;</html>');
0208       end
0209 
0210       % Store the uitable's handle within the pnContainer's userdata, for later use
0211       set(pnContainer,'userdata',[get(pnContainer,'userdata'), mtable]);  % add to parent userdata, so we have a handle for deletion
0212 
0213       % Enable multiple row selection, auto-column resize, and auto-scrollbars
0214       scroll = mtable.TableScrollPane;
0215       scroll.setVerticalScrollBarPolicy(scroll.VERTICAL_SCROLLBAR_AS_NEEDED);
0216       scroll.setHorizontalScrollBarPolicy(scroll.HORIZONTAL_SCROLLBAR_AS_NEEDED);
0217       jtable.setSelectionMode(javax.swing.ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
0218       jtable.setAutoResizeMode(jtable.AUTO_RESIZE_SUBSEQUENT_COLUMNS)
0219 
0220       % Set the jtable name based on the containing panel's tag
0221       basicTagName = get(pnContainer,'tag');
0222       jtable.setName([basicTagName 'Table']);
0223 
0224       % Move the selection to first table cell (if any data available)
0225       if (jtable.getRowCount > 0)
0226           jtable.changeSelection(0,0,false,false);
0227       end
0228 
0229       % Process optional args
0230       for argIdx = 1 : 2 : length(varargin)
0231           if argIdx<2
0232               % We need this pause to let java complete all table rendering
0233               % TODO: We should really use calls to awtinvoke() instead, though...
0234               pause(0.05);
0235           end
0236           if (length(varargin) > argIdx)   % ensure the arg value is there...
0237               varargin{argIdx}(1) = upper(varargin{argIdx}(1));  % property names always start with capital letters...
0238               propMethodName = ['set' varargin{argIdx}];
0239               if ismethod(mtable,propMethodName)
0240                   set(mtable,varargin{argIdx},varargin{argIdx+1});
0241               else
0242                   %javaMethod(propMethodName, jtable, varargin{argIdx+1});
0243                   set(jtable,varargin{argIdx},varargin{argIdx+1});
0244               end
0245           end
0246       end  % for argIdx
0247 
0248       % Create table manipulation buttons
0249       if buttonsFlag
0250           buttons = createManipulationButtons(pnContainer,mtable);
0251       else
0252           buttons = [];
0253       end
0254   %catch
0255       % Insert your code here
0256       %handleError;
0257   %end
0258 
0259 
0260 %% --- Executes on button press in btInsert.
0261 function buttons = createManipulationButtons(pnContainer, mtable)
0262 % pnContainer  handle to container uipanel
0263 % mtable       handle to mtable (Matlab) object
0264   %try
0265       btAppendRow = uicontrol('tag','btTableAppendRow', 'callback',@btTableAppendRow_Callback, 'position',  [10,5,60,20], 'string','Append',     'parent',pnContainer, 'userdata',mtable);
0266       btInsertRow = uicontrol('tag','btTableInsertRow', 'callback',@btTableInsertRow_Callback, 'position',  [80,5,60,20], 'string','Insert',     'parent',pnContainer, 'userdata',mtable);
0267       btDeleteRow = uicontrol('tag','btTableDeleteRow', 'callback',@btTableDeleteRow_Callback, 'position', [150,5,60,20], 'string','Delete',     'parent',pnContainer, 'userdata',mtable);
0268       btDeleteAll = uicontrol('tag','btTableDeleteAll', 'callback',@btTableDeleteAll_Callback, 'position', [220,5,60,20], 'string','Delete All', 'parent',pnContainer, 'userdata',mtable);
0269       btPrintAll  = uicontrol('tag','btTablePrintAll',  'callback',@btTablePrintAll_Callback,  'position', [290,5,60,20], 'string','Print',      'parent',pnContainer, 'userdata',mtable);
0270       buttons = [btInsertRow btAppendRow btDeleteRow btDeleteAll btPrintAll];
0271       if mtable.getNumRows < 1
0272           setVisibility(pnContainer, 'off');
0273       end
0274   %catch
0275       % Insert your code here
0276       %handleError;
0277   %end
0278 
0279 
0280 %% --- Executes on button press in btInsert.
0281 % Insert a new row immediately before the current row
0282 function btTableInsertRow_Callback(hObject, eventdata, handles)  %#ok
0283 % hObject    handle to btTableInsertRow (see GCBO)
0284 % eventdata  reserved - to be defined in a future version of MATLAB
0285 % handles    structure with handles and user data (see GUIDATA)
0286   %try
0287       mtable = get(hObject,'userdata');
0288       jtable = mtable.getTable;
0289 
0290       % Stop any current editing
0291       stopEditing(jtable);
0292 
0293       % Insert the new row immediately before the current row
0294       newRowData = cell(1,mtable.getNumColumns);  % empty data
0295       mtable.getTableModel.insertRow(max(0,jtable.getSelectedRow), newRowData);
0296   %catch
0297       % Insert your code here
0298       %handleError;
0299   %end
0300 
0301 
0302 %% --- Executes on button press in btAppend.
0303 % Insert a new row as the last row in the table
0304 function btTableAppendRow_Callback(hObject, eventdata, handles)  %#ok
0305 % hObject    handle to btTableAppendRow (see GCBO)
0306 % eventdata  reserved - to be defined in a future version of MATLAB
0307 % handles    structure with handles and user data (see GUIDATA)
0308   %try
0309       mtable = get(hObject,'userdata');
0310       jtable = mtable.getTable;
0311 
0312       % Stop any current editing
0313       stopEditing(jtable);
0314 
0315       % Add a new row at the bottom of the data table
0316       newRowData = cell(1,mtable.getNumColumns);  % empty data
0317       mtable.getTableModel.addRow(newRowData);
0318 
0319       % Move the selection to Column A of this new row
0320       jtable.changeSelection(jtable.getRowCount-1,0,false,false);
0321 
0322       % There must be at least one table row now, so display the table in any case
0323       mtable.setVisible(true);
0324       setVisibility(hObject, 'on');
0325   %catch
0326       % Insert your code here
0327       %handleError;
0328   %end
0329 
0330 
0331 %% --- Executes on button press in btDelete.
0332 % If there are any rows displayed, then delete the currently-selected row
0333 function btTableDeleteRow_Callback(hObject, eventdata, handles)  %#ok
0334 % hObject    handle to btTableDeleteRow (see GCBO)
0335 % eventdata  reserved - to be defined in a future version of MATLAB
0336 % handles    structure with handles and user data (see GUIDATA)
0337   %try
0338       mtable = get(hObject,'userdata');
0339       jtable = mtable.getTable;
0340 
0341       % Stop any current editing
0342       stopEditing(jtable);
0343 
0344       % If there are any rows displayed, then delete the currently-selected row
0345       rowCount = jtable.getRowCount;
0346       if (rowCount > 0)  % might be==0 during slow processing & user double-click
0347           currentRow = max(0,jtable.getSelectedRow);
0348           currentCol = max(0,jtable.getSelectedColumn);
0349           mtable.getTableModel.removeRow(currentRow);
0350           if currentRow >= rowCount-1
0351               jtable.changeSelection(currentRow-1, currentCol, false, false);
0352           end
0353       end
0354       if (jtable.getRowCount <= 0)
0355           %table.setVisible(false);
0356           setVisibility(hObject, 'off');
0357       end
0358   %catch
0359       % Insert your code here
0360       %handleError;
0361   %end
0362 
0363 
0364 %% --- Executes on button press in btDeleteAll.
0365 % Deletes all table rows
0366 function btTableDeleteAll_Callback(hObject, eventdata, handles)  %#ok
0367 % hObject    handle to btTableDeleteAll (see GCBO)
0368 % eventdata  reserved - to be defined in a future version of MATLAB
0369 % handles    structure with handles and user data (see GUIDATA)
0370   %try
0371       mtable = get(hObject,'userdata');
0372       jtable = mtable.getTable;
0373 
0374       % Stop any current editing
0375       stopEditing(jtable);
0376 
0377       % Delete all table rows
0378       mtable.setNumRows(0);
0379 
0380       % Hide irrelevant controls
0381       %mtable.setVisible(false);
0382       setVisibility(hObject, 'off');
0383   %catch
0384       % Insert your code here
0385       %handleError;
0386   %end
0387 
0388 
0389 %% --- Executes on button press in btPrint.
0390 % Prints the table via Excel
0391 function btTablePrintAll_Callback(hObject, eventdata, handles)  %#ok
0392 % hObject    handle to btTablePrintAll (see GCBO)
0393 % eventdata  reserved - to be defined in a future version of MATLAB
0394 % handles    structure with handles and user data (see GUIDATA)
0395   persistent hExcel
0396   try
0397       mtable = get(hObject,'userdata');
0398 
0399       % Try to open an Excel COM server
0400       % Note: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/odc_2003_ta/html/odc_landoffice03_vba.asp
0401       try
0402           % try to reuse an existing (pre-opened) COM server
0403           % If we can't access the ActiveX parent, it means it's closed
0404           parent = hExcel.parent;  %#ok
0405       catch
0406           hExcel = actxserver('excel.application');
0407       end
0408 
0409       % Try to open the requested document
0410       hExcel.Workbooks.Add;
0411 
0412       % Format field headers
0413       headers = cell(mtable.getColumnNames)';
0414       if ~isempty(headers)
0415           hExcel.Range(['A1:' n2a(length(headers)) '1']).Select;
0416           hExcel.Selection.Value = headers;
0417           hExcel.Selection.Font.Bold = true;                   % bold
0418           hExcel.Selection.Font.Color = hex2dec('0000FF');     % Red
0419           hExcel.Selection.Border.Item(4).Weight = 3;          % underline
0420           hExcel.Selection.Cells.HorizontalAlignment = -4108;  % =xlCenter
0421       end
0422 
0423       % Set the data from the table
0424       data = cell(mtable.data);
0425       if ~isempty(headers)
0426           hExcel.Range(['A2:' n2a(size(data,2)) num2str(1+size(data,1))]).Select;
0427           hExcel.Selection.Value = data;
0428       end
0429 
0430       % TODO: Change checkbox fields to boolean (TRUE/empty)
0431 
0432       % Other formats
0433       %hExcel.Cells.HorizontalAlignment = -4108;  % =xlCenter  % TODO: preserve original jtable column alignment
0434       hExcel.Cells.EntireColumn.AutoFit;
0435       hExcel.ActiveSheet.DisplayRightToLeft = false;
0436       set(hExcel.ActiveSheet.PageSetup, 'LeftMargin',  hExcel.InchesToPoints(0.1), ...
0437                                         'RightMargin', hExcel.InchesToPoints(0.1), ...
0438                                         'HeaderMargin',hExcel.InchesToPoints(0), ...
0439                                         'FooterMargin',hExcel.InchesToPoints(0.1), ...
0440                                         'TopMargin',120, ...
0441                                         'FitToPagesWide',1, ...
0442                                         'FitToPagesTall',1, ...
0443                                         'Orientation','xlPortrait', ...
0444                                         'LeftHeader','&D  &T', ...
0445                                         'CenterHeader',char(mtable.getTable.getName), ...
0446                                         'RightHeader','&G');
0447 
0448       % Send to printer
0449       hExcel.ActiveWindow.SelectedSheets.PrintOut;
0450 
0451       % Close the workbook
0452       invoke(hExcel.ActiveWindow,'close',false);
0453   catch
0454       % Insert your code here
0455       %handleError;
0456       err = lasterror;
0457       try  invoke(hExcel.ActiveWindow,'close',false);  catch  end;  % just in case of a printing error
0458       rethrow(err);
0459   end
0460 
0461 
0462 %% --- Convert col # format to 'A','B','C','AA',... format
0463 % Thanks Brett Shoelson, via CSSM
0464 function colStr = n2a(c)
0465   t = [floor((c-1)/26)+64, rem(c-1,26)+65];
0466   if (t(1)<65), t(1) = []; end
0467   colStr = char(t);
0468 
0469 
0470 %% --- Executes on button press in btInsert.
0471 function stopEditing(jtable)
0472   %try
0473       component = jtable.getEditorComponent;
0474       if ~isempty(component)
0475           event = javax.swing.event.ChangeEvent(component);
0476           jtable.editingStopped(event);
0477       end
0478   %catch
0479       % Insert your code here
0480       %handleError;
0481   %end
0482 
0483   
0484 %% --- Utility function to set visibility of row manipulation buttons
0485 function setVisibility(hObject, enableStr)
0486 % hObject    handle to some element within the figure
0487 % enableStr  'on' or 'off'
0488   %try
0489       hParent = ancestor(hObject,'figure');
0490       set(findall(hParent,'tag','btTableInsertRow'),'enable',enableStr);
0491       set(findall(hParent,'tag','btTableDeleteRow'),'enable',enableStr);
0492       set(findall(hParent,'tag','btTableDeleteAll'),'enable',enableStr);
0493       set(findall(hParent,'tag','btTablePrintAll'), 'enable',enableStr);
0494   %catch
0495       % Insert your code here
0496       %handleError;
0497   %end

Generated on Mon 31-Mar-2008 21:41:00 by m2html © 2003