Can you create GUI class elements in a loop?

5 views (last 30 days)
sicilian27
sicilian27 on 18 Jun 2015
Commented: sicilian27 on 19 Jun 2015
Hi everybody. I am writing a GUI in which 32 toggle buttons function as status indicators. I have chosen to use toggle buttons because of their clear appearance. However, creating 32 buttons in essentially the same manner is very tedious and cluttered. Is there more efficient a way I could do this?
Here is all the relevant information about my program. I am defining everything in a handle class:
classdef x_GUI < handle
properties
bit1
bit2
....
These properties are then initialized in a function:
function app = x_GUI
Now creating the elements in this function the tedious way works fine. For example,
app.bit1 = uicontrol('Style','togglebutton',....)
This correctly displays the elements in the GUI, allows me to reference them later (i.e. get(app.bit1,'Value')) and outputs "x_GUI with properties bit1: [1x1 UIControl] ..."
when the script is executed to let me know that the property in the class has been altered. But I have to do this 32 times.
So when I tried to write a loop to save time and code, the element displayed properly, but in "x_GUI with properties bit1: [ ]..."
meaning that the property in the class was not edited. I tried using a for loop with
sprintf(app.bit%d,i) = uicontrol(...)
and creating an array
bit_handles = {app.bit1 ...} and then doing bit_handles{i} = uicontrol(...).
Both created the elements properly, but neither actually referenced the property in the class meaning bit1: [ ] still. Essentially, my problem is actually creating handles for the elements that are based off of the properties in the class.
Does anyone know a way I could effectively reference class properties in a for loop? Thank you very much for your time!

Answers (1)

Jan
Jan on 18 Jun 2015
I'm not sure, what your problem is. So just some thoughts:
"sprintf(app.bit%d,i) = uicontrol(...)"? Do you mean:
for k = 1:32
app.(sprintf('bit%d', k)) = uicontrol(...)
end
Note that you hide an index in the name of the fields. Why not using an array instead?
for k = 1:32
app.bit(k) = uicontrol(...)
end
Then you can obtain and set the properties of all objects directly:
get(app.bit, 'Value')
set(app.bit, 'BackgroundColor', [1,1,0])
  1 Comment
sicilian27
sicilian27 on 19 Jun 2015
Thank you Jan. I don't know why I didn't think of just creating a single property 'bit' and using the array idea like that. That made things much easier and cleaner.

Sign in to comment.

Categories

Find more on Migrate GUIDE Apps in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!