Displaying text correctly on buttons

1 view (last 30 days)
Andy
Andy on 10 Apr 2013
I have a 10x10 grid of buttons and i want to set the text of each button to a random number between 1 and 100 which i have already generated. I am setting the text using the string attribute, but i only get a number displaying on two of the squares of my grid. I get the number displaying on the first square which is the bottom left and also on the square to the right of this, but the text is very far over to the right of the second square so is possibly cut off. If i view the attributes of the last button to be placed there is a string value associated with it, but it is just not visible. So i assume this is the case for the rest of the buttons Any help appreciated.
close all
clear all
clc
fh = figure;
c = hsv(20);
bgh = uibuttongroup();
x = 0;
y = 0;
x1 = .1;
y1 = .1;
num = randperm(100,100);
square = 1;
for i = 1:10
for j = 1:10
rbh1 = uicontrol(bgh,'Style','pushbutton',...
'Units','normalized','Position',[x y x1 y1]);
set(rbh1,'BackgroundColor',c(randi(20),:),'String',num(square),'ForegroundColor',[1 1 1]);
square = square + 1;
y = y + .1;
y1 = y1 + 1;
end
x = x + .1;
x1 = x1 + .1;
y = 0;
y1 = .1;
end
get(rbh1)

Accepted Answer

Sean de Wolski
Sean de Wolski on 10 Apr 2013
Hi Andy,
First, Good question +1.
The problem is with 'Position' in this line:
rbh1 = uicontrol(bgh,'Style','pushbutton',...
'Units','normalized','Position',[x y x1 y1]);
You increase x1 and y1 on each iteration. These are the width and height components of the position, not the corner coordinates. Thus every push button is getting bigger and lying in front of the previous buttons making it so you can't see the text. Instead just, use 0.1 for both of these:
rbh1 = uicontrol(bgh,'Style','pushbutton',...
'Units','normalized','Position',[x y 0.1 0.1]);
  1 Comment
Andy
Andy on 10 Apr 2013
Thanks a lot, that seems to have been my problem. I have also implemented Jan's suggestion as well for displaying the string

Sign in to comment.

More Answers (1)

Jan
Jan on 10 Apr 2013
Another problem is the type of the data for the String property: A string is expected, but num(square) is a double. Better:
..., 'String', sprintf('%d', num(square)), ...

Community Treasure Hunt

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

Start Hunting!