- 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;
How can I display a list box item as a string in a label in AppDesigner?
14 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
采纳的回答
Dave B
2021-9-29
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:
5 个评论
Dave B
2021-9-30
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.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Develop uifigure-Based Apps 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!