【问题标题】:Array of TButtons - how to control themTButton 数组 - 如何控制它们
【发布时间】:2016-12-21 16:40:39
【问题描述】:

我目前正在将“noughts and crosss”作为家庭作业。我生成了一个 10x10 的 TButton 对象数组,但我不知道它们是如何被调用的以及如何控制它们:

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;

我的按钮是否也在那个数组中?我必须说我在这里有点困惑。

【问题讨论】:

  • 你的代码真的是这样缩进的吗?很难阅读。不禁想到,在这个看似匆忙的粘贴练习中,您可能错过了重要的代码。

标签: delphi delphi-7 pascal


【解决方案1】:

您必须将每个新创建的按钮对象分配给适当的数组条目。

另一件重要的事情 - 在公共事件处理程序中,您可能想要确定按下了哪个按钮。可能的方式——使用对象字段标签

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;

【讨论】:

  • 更好的方法,子类化按钮类型并添加字段来保存行和列
  • @David 对初学者来说似乎有点矫枉过正
【解决方案2】:

在for循环末尾添加

pole[i][j] := h;

因为每次迭代你只是覆盖变量“h”,没有任何东西被添加到数组中。

【讨论】:

    猜你喜欢
    • 2012-01-15
    • 2010-11-04
    • 1970-01-01
    • 2013-02-09
    • 1970-01-01
    • 2018-04-06
    • 2011-12-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多