In one of my MATLAB projects, I want to add a button to an existing axes toolbar. The function for doing this is axtoolbarbtn:
axtoolbarbtn(tb,style,Name=Value)
However, I have found that the existing interfaces and behavior make it quite awkward to accomplish this task.
Here are my observations.
Adding a Button to the Default Axes Toolbar Is Unsupported
plot(1:10)
ax = gca;
tb = ax.Toolbar
Calling axtoolbarbtn on ax results in an error:
>> axtoolbarbtn(tb,"state")
Error using axtoolbarbtn (line 77)
Modifying the default axes toolbar is not supported.
Default Axes Toolbar Can't Be Distinguished from an Empty Toolbar
The Children property of the default axes toolbar is empty. Thus, it appears programmatically to have no buttons, just like an empty toolbar created by axtoolbar.
cla
plot(1:10)
ax = gca;
tb = ax.Toolbar;
tb.Children
ans = 0x0 empty GraphicsPlaceholder array.
tb2 = axtoolbar(ax);
tb2.Children
ans = 0x0 empty GraphicsPlaceholder array.
A Workaround
An empty axes toolbar seems to have no use except to initalize a toolbar before immediately adding buttons to it. Therefore, it seems reasonable to assume that an axes toolbar that appears to be empty is really the default toolbar. While we can't add buttons to the default axes toolbar, we can create a new toolbar that has all the same buttons as the default one, using axtoolbar("default"). And then we can add buttons to the new toolbar.
That observation leads to this workaround:
tb = ax.Toolbar;
if isempty(tb.Children)
tb = axtoolbar(ax,"default");
end
btn = axtoolbarbtn(tb);
As workarounds go, it's not horrible. It just seems a shame to have to delete and then recreate a toolbar just to be able to add a button to it.
The worst part about the workaround is that it is so not obvious. It took me a long time of experimentation to figure it out, including briefly giving it up as seemingly impossible.
The documentation for axtoolbarbtn avoids the issue. The most obvious example to write for axtoolbarbtn would be the first thing every user of it will try: add a toolbar button to the toolbar that gets created automatically in every call to plot. The doc page doesn't include that example, of course, because it wouldn't work. My Request
I like the axes toolbar concept and the axes interactivity that it promotes, and I think the programming interface design is mostly effective. My request to MathWorks is to modify this interface to smooth out the behavior discontinuity of the default axes toolbar, with an eye towards satisfying (and documenting) the general use case that I've described here.
One possible function design solution is to make the default axes toolbar look and behave like the toolbar created by axtoolbar("default"), so that it has Children and so it is modifiable.