Pavel Straka
Pavel Straka

Reputation: 51

Array of TButtons - how to control them

I am currently making "noughts and crosses" as homework. I generated a 10x10 array of TButton objects, but I don't know how they are called and how to control them:

Form1: TForm1;
  pole: array[1 .. 10, 1 .. 10] of TButton;
  h:TButton;

for i:=1 to 10 do
  for j:=1 to 10 do
  begin
    h:=TButton.Create(Self);
    h.Parent:=Self;
    h.Width:=50;
    h.Height:=50;
    h.Left:=((i+1)*50)-100;
    h.top:=((j+1)*50)-100;
    h.OnClick := hClick;
  end;

Are my buttons even in that array? I must say I am confused a bit here.

Upvotes: 1

Views: 693

Answers (2)

MBo
MBo

Reputation: 80232

You have to assign every newly created button object to appropriate array entry.

Another important thing - inside common event handler you probably want to determine what button is pressed. Possible way - use object field Tag

for i:=1 to 10 do
  for j:=1 to 10 do  begin
   h:=TButton.Create(Self);
   pole[i, j] := h;
   ... 
   h.OnClick := hClick;
   h.Tag := 10 * i + j; //store both row and column
end;


procedure ...hClick(Sender: TObject);
var
  i, j: integer;
begin
   i := (Sender as TButton).Tag div 10;  // extract row and column
   j := (Sender as TButton).Tag mod 10; 
   ...
end;

Upvotes: 8

A. L.
A. L.

Reputation: 761

At the end of for-loop add

pole[i][j] := h;

Because every iteration you just overwrite variable 'h' and nothing gets added into array.

Upvotes: 2

Related Questions