How can I display a list box item as a string in a label in AppDesigner?

13 Ansichten (letzte 30 Tage)
Dear Matlab Community,
I wanted to ask if it's possible to display a list box item, which is chosen by the user, as a string in a label. So for example if the user choses the list box item 'blue' then 'blue' should appear in the label. If the user choses 'red', 'red' should be displayed in the label. Is that possible? If yes, what does the code look like?
Thanks a lot!
Shanice

Akzeptierte Antwort

Dave B
Dave B am 29 Sep. 2021
Yes this is possible. You can create a listbox, and a label, and assign a callback to the listbox that sets the label.
In general, to make components in apps do things when you interact with them, you assing a function to a property that ends in Fcn. These can point to functions you define in your m-code, or for simple things you can just define them inline as I did below.
Here's a demo of a programmatically generated app:
u = uifigure;
lst = uilistbox(u,'Items',["Red" "Green" "Blue" "Purple"]);
lbl = uilabel(u,'Text','Red');
lbl.Position([1 3])=[300 100];
lst.ValueChangedFcn = @(~,~)set(lbl,'Text',lst.Value);
If you use App Designer (click Apps at top, then 'Design App') the process looks like this:
  • Drag ListBox and Label into your app
  • Click 'Code View' at the top right
  • Click the + button in the Callbacks section of the Code Browser at left
  • An Add Callback Function dialog will pop up, you can select your ListBox component which only has one available callback (ValueChangedFcn) and hit Add callback
  • MATLAB will generate a function for you with value holding the selected item. Just add another line to set the Text property of the label: app.Label.Text = value;
  5 Kommentare
Dave B
Dave B am 30 Sep. 2021
Sure...
It looks like you've added the callback function and just need to enter in the code.
Click in the ListBoxValueChanged item in the callbacks list, that will bring you to a spot of code you can edit:
Here's some code I put in that did the trick:
The value = app.ListBox.Value; is added by default from MATLAB, this just gives you a variable name to shorten things up.
The ind = strcmp(app.ListBox.ItemsData, value); line compares the character arrays in ItemsData to the one in value, giving a vector of logicals that can be used to index into Items (i.e. it says which ItemsData is selected, which corresponds to which Items is selected).
The app.Label.Text = app.ListBox.Items(ind); line uses the index to get the character array in Items, then it assigns that array to the label objects text property.
Shanice Steinecke
Shanice Steinecke am 30 Sep. 2021
Thank you so much for the explanation!!! It works :)

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Develop uifigure-Based Apps finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by