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

CheckboxList

September 10, 2014 24 Comments

Several years ago I blogged about using a checkbox-tree in Matlab. A few days ago there was a question on the Matlab Answers forum asking whether something similar can be done with Matlab listboxes, i.e. add checkboxes next to each list item. There are actually several alternatives for this and I thought this could be a good opportunity to discuss them:

  • The HTML image variant
  • MathWorks CheckBoxList
  • JIDE’s CheckBoxList
  • ActiveX and other alternatives
  • Matlab uitable in disguise

MathWorks CheckBoxList
MathWorks CheckBoxList

The HTML image variant

The simplest alternative is to use small icon images checked and unchecked as part of the listbox item labels. As I explained last year, listboxes (like all other Matlab uicontrols that rely on underlying Java Swing components), support HTML and can be formatted using HTML images. For example:

Matlab listbox with HTML image icons
Matlab listbox with HTML image icons

In order to check/uncheck items in the listbox, we can trap the underlying Java component’s MouseClickedCallback using the findjobj utility:

% Assume checked.gif, unchecked.gif are 16x16 icons
prefix = ['<html><img src="file:///' strrep(path_of_icon_files),'\','/') '/unchecked.gif" height=16 width=16 />'];
sampleData = strcat(prefix, {'first', 'Second', 'Third', 'and last'});  % all items are unchecked at first
hListbox = uicontrol(...);
jScrollPane = findjobj(hListbox);
jListbox = handle(jScrollPane.getViewport.getView, 'CallbackProperties');
jListbox.MouseClickedCallback = {@mouseClickedFcn,hListbox};
function mouseClickedFcn(jListbox, jEventData, hListbox)
   % Get the clicked item and row index
   clickedX = jEventData.getX;
   clickedY = jEventData.getY;
   if clickedX > 15,  return;  end  % did not click a checkbox so bail out
   clickedRow = jListbox.locationToIndex(java.awt.Point(clickedX,clickedY)) + 1;  % Matlab row index = Java row index+1
   if clickedRow <= 0,  return;  end  % clicked not on an item - bail out
   strs = get(hListbox,'String');
   clickedItem = strs{clickedRow};
   % Switch the icon between checked.gif <=> unchecked.gif
   if strfind(clickedItem,'unchecked')
       strs{clickedRow} = strrep(clickedItem,'unchecked','checked');
   else
       strs{clickedRow} = strrep(clickedItem,'checked','unchecked');
   end
   set(hListbox,'String',strs);  % update the list item
end

% Assume checked.gif, unchecked.gif are 16x16 icons prefix = ['<html><img src="file:///' strrep(path_of_icon_files),'\','/') '/unchecked.gif" height=16 width=16 />']; sampleData = strcat(prefix, {'first', 'Second', 'Third', 'and last'}); % all items are unchecked at first hListbox = uicontrol(...); jScrollPane = findjobj(hListbox); jListbox = handle(jScrollPane.getViewport.getView, 'CallbackProperties'); jListbox.MouseClickedCallback = {@mouseClickedFcn,hListbox}; function mouseClickedFcn(jListbox, jEventData, hListbox) % Get the clicked item and row index clickedX = jEventData.getX; clickedY = jEventData.getY; if clickedX > 15, return; end % did not click a checkbox so bail out clickedRow = jListbox.locationToIndex(java.awt.Point(clickedX,clickedY)) + 1; % Matlab row index = Java row index+1 if clickedRow <= 0, return; end % clicked not on an item - bail out strs = get(hListbox,'String'); clickedItem = strs{clickedRow}; % Switch the icon between checked.gif <=> unchecked.gif if strfind(clickedItem,'unchecked') strs{clickedRow} = strrep(clickedItem,'unchecked','checked'); else strs{clickedRow} = strrep(clickedItem,'checked','unchecked'); end set(hListbox,'String',strs); % update the list item end

Finally, when we process the selected list item(s), we can simply check whether they contain ‘unchecked.gif’ or ‘checked.gif’. Pretty straight-forward stuff.

MathWorks CheckBoxList

com.mathworks.mwswing.checkboxlist.CheckBoxList is a JList extension that displays a list of labels in a list with a checkbox next to each label. The labels’ checkboxes can be set, unset and queried using methods supplied by the CheckBoxList class or its com.mathworks.mwswing.checkboxlist.DefaultListCheckModel model:

% First create the data model
jList = java.util.ArrayList;  % any java.util.List will be ok
jList.add(0,'First');
jList.add(1,'Second');
jList.add(2,'Third');
jList.add(3,'and last');
% Next prepare a CheckBoxList component within a scroll-pane
jCBList = com.mathworks.mwswing.checkboxlist.CheckBoxList(jList);
jScrollPane = com.mathworks.mwswing.MJScrollPane(jCBList);
% Now place this scroll-pane within a Matlab container (figure or panel)
[jhScroll,hContainer] = javacomponent(jScrollPane,[10,10,80,65],gcf);
% Update some items' state programmatically
jCBModel = jCBList.getCheckModel;
jCBModel.checkAll;
jCBModel.uncheckIndex(1);
jCBModel.uncheckIndex(3);
% Respond to checkbox update events
jhCBModel = handle(jCBModel, 'CallbackProperties');
set(jhCBModel, 'ValueChangedCallback', @myMatlabCallbackFcn);

% First create the data model jList = java.util.ArrayList; % any java.util.List will be ok jList.add(0,'First'); jList.add(1,'Second'); jList.add(2,'Third'); jList.add(3,'and last'); % Next prepare a CheckBoxList component within a scroll-pane jCBList = com.mathworks.mwswing.checkboxlist.CheckBoxList(jList); jScrollPane = com.mathworks.mwswing.MJScrollPane(jCBList); % Now place this scroll-pane within a Matlab container (figure or panel) [jhScroll,hContainer] = javacomponent(jScrollPane,[10,10,80,65],gcf); % Update some items' state programmatically jCBModel = jCBList.getCheckModel; jCBModel.checkAll; jCBModel.uncheckIndex(1); jCBModel.uncheckIndex(3); % Respond to checkbox update events jhCBModel = handle(jCBModel, 'CallbackProperties'); set(jhCBModel, 'ValueChangedCallback', @myMatlabCallbackFcn);

This results in the following image:

MathWorks CheckBoxList
MathWorks CheckBoxList

We can query the various checked/unchecked states programmatically:

>> jCBList.getCheckedValues
ans =
[First, Third]
>> jCBList.getCheckedIndicies'
ans =
           0       2
>> jCBModel.isIndexChecked(0)
ans =
     1    % =true

>> jCBList.getCheckedValues ans = [First, Third] >> jCBList.getCheckedIndicies' ans = 0 2 >> jCBModel.isIndexChecked(0) ans = 1 % =true

JIDE’s CheckBoxList

There is also an unrelated JIDE equivalent: com.jidesoft.swing.CheckBoxList. Readers are referred to the JIDE documentation for additional details.
The basic idea is the same as with the MathWorks CheckBoxList: we create the data model, then create a CheckBoxList component within a JScrollPane and place this onscreen using the javacomponent function. We can then modify or query the data model programmatically, and set various callback functions to process user events.

% Prepare the data model as above
% Now display onscreen:
jCBList = com.jidesoft.swing.CheckBoxList(jList.toArray)
jScrollPane = com.mathworks.mwswing.MJScrollPane(jCBList);
[jhScroll,hContainer] = javacomponent(jScrollPane, [120,10,80,65], gcf);
% Do some programmatic updates:
jCBList.selectAll;  % reverse: jCBList.selectNone
jCBList.setCheckBoxListSelectedIndices([0,2]);

% Prepare the data model as above % Now display onscreen: jCBList = com.jidesoft.swing.CheckBoxList(jList.toArray) jScrollPane = com.mathworks.mwswing.MJScrollPane(jCBList); [jhScroll,hContainer] = javacomponent(jScrollPane, [120,10,80,65], gcf); % Do some programmatic updates: jCBList.selectAll; % reverse: jCBList.selectNone jCBList.setCheckBoxListSelectedIndices([0,2]);

The appearance is very similar to the MathWorks CheckBoxList, except that JIDE’s CheckBoxList has slightly less space between the list rows, and between the checkboxes and labels. The main difference between these components is not in their visual appearance but rather in their supported functionalities (internal methods) – some people might prefer the MathWorks component, others might like JIDE better. To see these functionalities, use my uiinspect and/or checkClass utilities.
For additional information on the MathWorks and JIDE components, and how to investigate and customize them, see Chapter 5 of my Matlab-Java programming book.

ActiveX and other alternatives

If you are running on Windows, you could use ActiveX controls that implement checkbox list functionality. One such control that is pretty standard is Microsoft’s MSComctlLib.ListViewCtrl.2. I showed an example of ListViewCtrl usage a few years ago, and readers are referred there for details. Here is the end result:

Sorted ListViewCtrl
Sorted ListViewCtrl

Granted, this is more of a table having a checkbox column than a listbox, but you can easily make the ListViewCtrl have only a single column.
In addition to this standard ListViewCtrl control, there are plenty of other third-party ActiveX or Java controls that can more-or-less easily be integrated in our Matlab GUI. The drawback of ActiveX is that it only works on a limited set of platforms, whereas the Java-based components (either MathWorks or JIDE) work on all Matlab installations.

Matlab uitable in disguise

As a variant of the idea of using a table with a checkbox first column, we could use Matlab’s builtin uitable function, as suggested by Sebastian below. Here is a simple code snippet illustrating this idea:

data = {true,'First'; false,'Second'; true,'Third'; false,'and last'};
hTable = uitable('Data',data,'RowName',[],'ColumnName',[],'BackgroundColor',[1,1,1],'Position',[10,10,100,70],'ColumnWidth',{20,60});

data = {true,'First'; false,'Second'; true,'Third'; false,'and last'}; hTable = uitable('Data',data,'RowName',[],'ColumnName',[],'BackgroundColor',[1,1,1],'Position',[10,10,100,70],'ColumnWidth',{20,60});

Matlab uitable with checkbox column
Matlab uitable with checkbox column

Anyway, let no one say ever again that Matlab GUI is boring. It is not. It is only limited by our imagination and our willingness to find and customize components that implement our requirements. There are plenty of alternatives out there, we just need to reach out and use them. If you can’t do it yourself, you could always use an external consultant like me to help you.

Related posts:

  1. Customizing listbox/combobox items – Matlab listboxes can be customized using custom Java cell-renderers. ...
  2. Listbox layout customization – Matlab's listbox layout can be modified to display multiple item columns and different inter-cell margins. ...
  3. Listbox selection hacks – Matlab listbox selection can be customized in a variety of undocumented ways. ...
  4. Setting listbox mouse actions – Matlab listbox uicontrol can be modified to detect mouse events for right-click context menus, dynamic tooltips etc....
  5. Smart listbox & editbox scrollbars – Matlab listbox and multi-line editbox scrollbars can easily be made smarter, for improved appearance. ...
  6. Tri-state checkbox – Matlab checkboxes can easily be made to support tri-state functionality....
ActiveX GUI Internal component Java
Print Print
« Previous
Next »
24 Responses
  1. Etienne September 18, 2014 at 01:13 Reply

    In your Mathworks CheckBoxList example the ‘ValueChangedCallback’ listens for changes in the selected listbox items (e.g. first or third). Which callback would you use to listen for check/uncheck property changes? These selection are not registered with the ‘ValueChangedCallback’…

    • Yair Altman September 18, 2014 at 03:22 Reply

      You need to set the ValueChangedCallback of the control’s data (check) model, not of the control:

      jhCBModel = handle(jCBList.getCheckModel, 'CallbackProperties');
      set(jhCBModel, 'ValueChangedCallback', @myMatlabCallbackFcn);

      jhCBModel = handle(jCBList.getCheckModel, 'CallbackProperties'); set(jhCBModel, 'ValueChangedCallback', @myMatlabCallbackFcn);

      It makes sense if you think about it: listbox values determine which items are selected; check-model values determine which items are checked. It’s not the same thing – listbox items can be checked/unchecked independently of whether or not they are selected.

  2. Customizing listbox/combobox items | Undocumented Matlab September 18, 2014 at 01:48 Reply

    […] Customizing listbox/combobox items […]

  3. sebastian September 19, 2014 at 07:26 Reply

    FWIW:

    Another possibility is to use an uitable, with its first column displaying the checkboxes (with logical column format) and the second column showing the non-editable list items.
    Switching off row and column headers, as well as row-striping this looks pretty much just like a list view.

    • Yair Altman September 19, 2014 at 08:30 Reply

      Thanks for the comment Sebastian. It is a logical extension of the ActiveX idea, but you are of course correct that it should be made explicit, since using a uitable is a better solution (portability, performance, stability, maintainability) than the ActiveX control. I’ve updated the article with the uitable variant. Thanks again!

      • Sebastian November 13, 2014 at 07:32

        Hi Yair,

        thanks for this. What if I want to add/remove/update the java list items after creating the object?

        Cheers,
        Sebatian

      • Yair Altman November 13, 2014 at 08:00

        @Sebastian – I’m not sure to which of the Java objects you refer exactly. In any case you can use one of the built-in functions methods or methodsview, or my uiinspect or checkClass utilities, to see which methods (functions) are exposed (supported) by the Java objects. If you need specific examples search my blog or Matlab-Java book. If you need specific advise, you can contact me by email for a short consulting.

  4. Sebastian November 13, 2014 at 08:24 Reply

    Yair,

    thanks for your reply. I’ve tried with your fanstastic uiinspect() function but I was not able to find anything interesting. What I mean is, imagine you have the following code:

    % First create the data model
    jList = java.util.ArrayList;  % any java.util.List will be ok
    jList.add(0,'First');
    jList.add(1,'Second');
    jList.add(2,'Third');
    jList.add(3,'and last');
     
    % Next prepare a CheckBoxList component within a scroll-pane
    jCBList = com.mathworks.mwswing.checkboxlist.CheckBoxList(jList);
    jScrollPane = com.mathworks.mwswing.MJScrollPane(jCBList);
     
    % Now place this scroll-pane within a Matlab container (figure or panel)
    [jhScroll,hContainer] = javacomponent(jScrollPane,[10,10,80,65],gcf);

    % First create the data model jList = java.util.ArrayList; % any java.util.List will be ok jList.add(0,'First'); jList.add(1,'Second'); jList.add(2,'Third'); jList.add(3,'and last'); % Next prepare a CheckBoxList component within a scroll-pane jCBList = com.mathworks.mwswing.checkboxlist.CheckBoxList(jList); jScrollPane = com.mathworks.mwswing.MJScrollPane(jCBList); % Now place this scroll-pane within a Matlab container (figure or panel) [jhScroll,hContainer] = javacomponent(jScrollPane,[10,10,80,65],gcf);

    which is actually your example. Now imagine you need to add/remove/rename one of the checkboxlist items. I would imagine I should find a method which ‘updates’ the jCBList or something similar…obviously I don’t want to remove the jScrollPane and create a new one with a new jList.
    Does my question make any sense?

    Cheers,

    Sebastian

    • Nadav December 6, 2014 at 23:16 Reply

      this is interesting – is there a way to update the entries in the list?

    • Miloslav September 5, 2017 at 15:01 Reply

      I’m also interested in modifying list elements.
      I’m using R2016b on Windows (x64).

      I could modify the existing elements like:

      cbmodel = javax.swing.DefaultListModel;
      cbmodel.addElement('Test A'); %any of the following two will work
      cbmodel.insertElementAt('Test B', 1);
       
      jCBList = com.mathworks.mwswing.checkboxlist.CheckBoxList(cbmodel);
      jScrollPane2 = com.mathworks.mwswing.MJScrollPane(jCBList);
       
      %draw it
      [jhScroll,hContainer] = javacomponent(jScrollPane2,[0,0,200,200],gcf);
      set(hContainer,'units','norm', 'tag','modelList'); %set 'tag' to find it later
       
      %to modify the existing elements
      oList = findobj('Tag','nameList'); %return JavaWrapper
      zz = oList.JavaPeer; %return MJScroollPane
      zzz = zz.getViewport().getView(); % return CheckBoxList
      list = zzz.getModel(); % return DefaultListModel
      % or directly
      %list = oList.JavaPeer.getViewport().getView().getModel();
       
      list.clear(); % clear the list
      methods(list);
      % will print you this methods
      %DefaultListModel        equals                  isEmpty                 set                     
      %add                     firstElement            lastElement             setElementAt            
      %addElement              get                     lastIndexOf             setSize                 
      %addListDataListener     getClass                notify                  size                    
      %capacity                getElementAt            notifyAll               toArray                 
      %clear                   getListDataListeners    remove                  toString                
      %contains                getListeners            removeAllElements       trimToSize              
      %copyInto                getSize                 removeElement           wait                    
      %elementAt               hashCode                removeElementAt         
      %elements                indexOf                 removeListDataListener  
      %ensureCapacity          insertElementAt         removeRange             
       
      list.addElement('TEST');
      list.addElement('Element 2');
      list.setElementAt('replaced previous TEST',0);
      list.insertElementAt('TEST 2',1); % this will allow you really add more elements to the list without exception "IndexOutOfBoundsException"
       
      %OR
      %now you can manipulate the list elements by replacing the model with the new one
      model = javax.swing.DefaultListModel;
      model.addElement('new TEST'); %it works if you add 1-3 elements
      %now, add new element to the list at certain position
      model.insertElementAt('blabla', 1); % second argument is index, start with 0
       
      zzz.setModel(model); % and replace old model with new one in the CheckBoxList

      cbmodel = javax.swing.DefaultListModel; cbmodel.addElement('Test A'); %any of the following two will work cbmodel.insertElementAt('Test B', 1); jCBList = com.mathworks.mwswing.checkboxlist.CheckBoxList(cbmodel); jScrollPane2 = com.mathworks.mwswing.MJScrollPane(jCBList); %draw it [jhScroll,hContainer] = javacomponent(jScrollPane2,[0,0,200,200],gcf); set(hContainer,'units','norm', 'tag','modelList'); %set 'tag' to find it later %to modify the existing elements oList = findobj('Tag','nameList'); %return JavaWrapper zz = oList.JavaPeer; %return MJScroollPane zzz = zz.getViewport().getView(); % return CheckBoxList list = zzz.getModel(); % return DefaultListModel % or directly %list = oList.JavaPeer.getViewport().getView().getModel(); list.clear(); % clear the list methods(list); % will print you this methods %DefaultListModel equals isEmpty set %add firstElement lastElement setElementAt %addElement get lastIndexOf setSize %addListDataListener getClass notify size %capacity getElementAt notifyAll toArray %clear getListDataListeners remove toString %contains getListeners removeAllElements trimToSize %copyInto getSize removeElement wait %elementAt hashCode removeElementAt %elements indexOf removeListDataListener %ensureCapacity insertElementAt removeRange list.addElement('TEST'); list.addElement('Element 2'); list.setElementAt('replaced previous TEST',0); list.insertElementAt('TEST 2',1); % this will allow you really add more elements to the list without exception "IndexOutOfBoundsException" %OR %now you can manipulate the list elements by replacing the model with the new one model = javax.swing.DefaultListModel; model.addElement('new TEST'); %it works if you add 1-3 elements %now, add new element to the list at certain position model.insertElementAt('blabla', 1); % second argument is index, start with 0 zzz.setModel(model); % and replace old model with new one in the CheckBoxList

      If you add mode elements (using addElement method) than the original list had you will get :
      “Exception in thread “AWT-EventQueue-0″ java.lang.IndexOutOfBoundsException: Index: 1, Size: 1”

  5. Nadav November 30, 2014 at 23:03 Reply

    Hi Yair,
    Can you please comment on whether or not the MathWorks CheckBoxList will compile into an executable?

    Thanks,
    Nadav

    • Yair Altman November 30, 2014 at 23:41 Reply

      @Nadav – yes it should, it is part of the MCR.

  6. Loops September 2, 2015 at 15:18 Reply

    Hello Yair

    Nice example!!

    When I add the JScrollPane into a matlab panel, I want set its Units normalized and fill the matlab panel.
    But its Origin Position exceeds the matlab panel and doesn’t fit in the matlab panel precisely.
    How do I fix it?

    hf = figure;
    hpanel = uipanel('Parent', hf);
    [jhScroll, hContainer] = javacomponent(jScrollPane, [2 2 60 80], hpanel);
    set(hContainer, 'Units','normalized', 'Position', [0 0 1 1]);

    hf = figure; hpanel = uipanel('Parent', hf); [jhScroll, hContainer] = javacomponent(jScrollPane, [2 2 60 80], hpanel); set(hContainer, 'Units','normalized', 'Position', [0 0 1 1]);

    • Yair Altman September 3, 2015 at 07:45 Reply

      @Loops – Your code seems to work well for me. I do not understand your problem, nor what you mean by “Origin Position”.

    • Loops September 9, 2015 at 16:38 Reply
      hf = figure;
      hpanel = uipanel('Parent', hf);
      uicontrol('Parent', hpanel, 'Style', 'listbox','Units', 'normalized','Position',[0,0,1,1],'Background','white');

      hf = figure; hpanel = uipanel('Parent', hf); uicontrol('Parent', hpanel, 'Style', 'listbox','Units', 'normalized','Position',[0,0,1,1],'Background','white');

      Here is the result I builted.
      You could see there are “a little” differences between Java component and Matlab component.
      The red and green circle are what I mean the “Origin Position”.
      https://www.dropbox.com/s/kgvgd0hxcasovhm/Shift.png?dl=0

      • Yair Altman September 10, 2015 at 03:02

        @Loops – this is because of your uipanel (hpanel). Instead, place your javacomponent directly within the figure, rather than a uipanel:

        [jhScroll, hContainer] = javacomponent(jScrollPane, [2 2 60 80], hf);

        [jhScroll, hContainer] = javacomponent(jScrollPane, [2 2 60 80], hf);

        Alternatively, set your parent uipanel to have no border line:

        hpanel = uipanel('Parent', hf, 'BorderType', 'none');

        hpanel = uipanel('Parent', hf, 'BorderType', 'none');

  7. Xiangrui Li December 30, 2015 at 15:15 Reply

    I was searching for checkbox list solution, and found this thread. Thanks Yair for providing different solutions! After playing with the options, here is my two cents.

    (1) The MathWorks CheckBoxList looks nice, but as already asked here, I did not find a solution to add/remove an item. So it is not ideal for my purpose.
    (2) I did not try ActiveX method, since I want a system independent solution.
    (3) The Matlab uitable method is very easy to use. I was trying to use it until I realize that there is no programmatic way to set the selected item. Another minor issue is that it seems there is no way to set alignment to left in case that the content exceeds the defined width.

    So I ended up the Matlab listbox method. I am sharing what I did with the listbox method, in case it is useful to others. It is almost the same as the the first method Yair described, but no java and image are used. Instead, I use two special characters for check and uncheck marks.

    feature('DefaultCharacterSet', 'UTF-8'); % needed for old matlab
    checked = 9746; % square with X inside
    unchecked = 9744; % empty square
    h = uicontrol('Style', 'list', 'Position', [10 10 100 80], 'Callback', @select_cb, ...
        'FontSize', 10, ... % affect the check mark coordinate detection
        'String', {[checked ' First'] [unchecked ' Second'] [checked ' Third'] [unchecked ' and last']});
     
    function select_cb(h, ~)
    i = get(h, 'Value');
    x = get(0, 'PointerLocation'); % figure CurrentPoint is not reliable
    pos = get(gcf, 'Position') + get(h, 'Position');
    x = x(1) - pos(1); % x coordinate of mouse click
    if x>2 && x<12 % related to FontSize, and maybe FontName
        str = get(h, 'String');
        if str{i}(1) ==  9746 % was checked
            str{i}(1) = 9744;
            fprintf('Item %g unchecked and selected.n', i);
        else
            str{i}(1) = 9746;
            fprintf('Item %g checked and selected.n', i);
        end
        set(h, 'String', str);
    else
        fprintf('Item %g selected.n', i);
    end

    feature('DefaultCharacterSet', 'UTF-8'); % needed for old matlab checked = 9746; % square with X inside unchecked = 9744; % empty square h = uicontrol('Style', 'list', 'Position', [10 10 100 80], 'Callback', @select_cb, ... 'FontSize', 10, ... % affect the check mark coordinate detection 'String', {[checked ' First'] [unchecked ' Second'] [checked ' Third'] [unchecked ' and last']}); function select_cb(h, ~) i = get(h, 'Value'); x = get(0, 'PointerLocation'); % figure CurrentPoint is not reliable pos = get(gcf, 'Position') + get(h, 'Position'); x = x(1) - pos(1); % x coordinate of mouse click if x>2 && x<12 % related to FontSize, and maybe FontName str = get(h, 'String'); if str{i}(1) == 9746 % was checked str{i}(1) = 9744; fprintf('Item %g unchecked and selected.n', i); else str{i}(1) = 9746; fprintf('Item %g checked and selected.n', i); end set(h, 'String', str); else fprintf('Item %g selected.n', i); end

  8. Xiangrui Li June 21, 2016 at 03:45 Reply

    Following Yair’s nice information, I played with JIDE checkbox list, and figured out the way to add/remove checkbox list dynamically for my purpose. Compared to my previous post using two special characters as checked and unchecked boxes, JIDE CheckBoxList contains true checkbox, so there is no need to compute the list item by mouse click location, which depends on font size.

    Another feature which fits my need very well is that JIDE CheckBoxList can be ClickInCheckBoxOnly, which separates check event and selection event. This is different from mathworks CheckBoxList where mouse selection always does check/uncheck, but much like uitable, while uitable has no programmatic way to select an item.

    Here is some sample code:

    % set up model
    jCBList = com.jidesoft.swing.CheckBoxList;
    jCBList.setModel(javax.swing.DefaultListModel); % dynamic items
    % jCBList.ClickInCheckBoxOnly = true; % it's default
    jCBList.setSelectionMode(0); % I need single selection
     
    % Now display onscreen:
    jScrollPane = com.mathworks.mwswing.MJScrollPane(jCBList);
    javacomponent(jScrollPane, [10,40,80,80], gcf);
     
    % add some items and set check/selecttion
    jCBList.getModel.addElement('First'); % add item to end
    jCBList.getModel.addElement('Third'); % add item to end
    jCBList.getModel.insertElementAt('Second', 1); % insert item as 2nd item
    % jCBList.getModel.removeElementAt(1); % remove 2nd item
    jCBList.addCheckBoxListSelectedIndex(2); % check 3rd item
    jCBList.setSelectedIndex(1); % select 2nd item (highlight)
     
    % set up callback
    h = handle(jCBList, 'CallbackProperties');
    set(h, 'MouseClickedCallback', @mouseFcn);
     
    % callback
    function mouseFcn(h, ~)
       fprintf('Item %g selectedn', h.getSelectedIndex+1);
       fprintf('Item(s) ');
       fprintf('%g ', h.getCheckBoxListSelectedIndices+1);
       fprintf('checkedn');
    end

    % set up model jCBList = com.jidesoft.swing.CheckBoxList; jCBList.setModel(javax.swing.DefaultListModel); % dynamic items % jCBList.ClickInCheckBoxOnly = true; % it's default jCBList.setSelectionMode(0); % I need single selection % Now display onscreen: jScrollPane = com.mathworks.mwswing.MJScrollPane(jCBList); javacomponent(jScrollPane, [10,40,80,80], gcf); % add some items and set check/selecttion jCBList.getModel.addElement('First'); % add item to end jCBList.getModel.addElement('Third'); % add item to end jCBList.getModel.insertElementAt('Second', 1); % insert item as 2nd item % jCBList.getModel.removeElementAt(1); % remove 2nd item jCBList.addCheckBoxListSelectedIndex(2); % check 3rd item jCBList.setSelectedIndex(1); % select 2nd item (highlight) % set up callback h = handle(jCBList, 'CallbackProperties'); set(h, 'MouseClickedCallback', @mouseFcn); % callback function mouseFcn(h, ~) fprintf('Item %g selectedn', h.getSelectedIndex+1); fprintf('Item(s) '); fprintf('%g ', h.getCheckBoxListSelectedIndices+1); fprintf('checkedn'); end

  9. Fabrizio May 3, 2017 at 12:39 Reply

    Hi Yair and many compliments for your post.
    I’m a beginner with Java in Matlab and I’ve a simple question to ask.
    After a selection, I wish to disable the panel containing the Mathworks checkboxlist.

    I noticed that

    set(findall(hpanel, '-property', 'enable'), 'enable', 'off')

    set(findall(hpanel, '-property', 'enable'), 'enable', 'off')

    doesn’t work.

    Furthermore

    jhScroll.setEnable(0)

    jhScroll.setEnable(0)

    doen’t produce any effects on the java component.
    On the contrary jhScroll.setVisible works as the name suggests.

    Where do I fail? Is it a known issue?
    Thanks in advance for your reply.

    • Yair Altman December 3, 2017 at 13:59 Reply

      @Fabrizio –

      jCBList.setEnabled(false)  % or: jCBList.setEnabled(0)

      jCBList.setEnabled(false) % or: jCBList.setEnabled(0)

  10. JoeB December 19, 2017 at 18:14 Reply

    Hi Yair, Thanks for this. When I try the following code in ML 2017a, I get a list that returns IsEnabled as false but still allows the user to change the checkbox values and does not appear greyed out. Any idea what I’m missing? Thanks:

    % First create the data model
    jList = java.util.ArrayList;  % any java.util.List will be ok
    jList.add(0,'First');
    jList.add(1,'Second');
    jList.add(2,'Third');
    jList.add(3,'and last');
     
    % Next prepare a CheckBoxList component within a scroll-pane
    jCBList = com.mathworks.mwswing.checkboxlist.CheckBoxList(jList);
    jScrollPane = com.mathworks.mwswing.MJScrollPane(jCBList);
     
    % Now place this scroll-pane within a Matlab container (figure or panel)
    [jhScroll,hContainer] = javacomponent(jScrollPane,[10,10,80,65],gcf);
     
    jCBList.setEnabled(0)

    % First create the data model jList = java.util.ArrayList; % any java.util.List will be ok jList.add(0,'First'); jList.add(1,'Second'); jList.add(2,'Third'); jList.add(3,'and last'); % Next prepare a CheckBoxList component within a scroll-pane jCBList = com.mathworks.mwswing.checkboxlist.CheckBoxList(jList); jScrollPane = com.mathworks.mwswing.MJScrollPane(jCBList); % Now place this scroll-pane within a Matlab container (figure or panel) [jhScroll,hContainer] = javacomponent(jScrollPane,[10,10,80,65],gcf); jCBList.setEnabled(0)

    • Yair Altman January 11, 2018 at 13:49 Reply

      @JoeB – the Mathworks’ CheckBoxList has a bug with this: the list is indeed disabled in the sense that you cannot change the selected item(s), but it is not fully disabled in the sense that you can still check/uncheck the checkboxes, even if you try to do jCBList.getCellRenderer.setEnabled(0).

      Instead, you can use JIDE’s CheckBoxList, which does not have this bug.

  11. Arun Joe Joseph November 5, 2019 at 12:22 Reply

    Is it possible to use this Matlab CheckboxList along with GUIDE? I tried using this in a GUIDE app, and it seems that I cannot pass GUIDE arguments like handles structure to myMatlabCallbackFcn?

    Also In myMatlabCallbackFcn, how can I access the Checked Values, as in the names corresponding to the checked values? I tried using jCBList.getCheckedValues, but I am not able to access jCBList inside my callback function.

  12. Jianfei November 28, 2020 at 16:07 Reply

    I have tried the MathWorks CheckBoxList in Matlab 2015b. For whatever the reason, I can’t change the font properties. I can change the font color, but changing font properties like font family, font size, bold and italic will not take any effect.

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