Delphi: TImage数组

4
这是我的整个代码:
    unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, ExtCtrls;

type
  TForm1 = class(TForm)
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;
  Images: array[0..29,0..39] of TImage; //array
implementation

{$R *.dfm}
//form create
procedure TForm1.FormCreate(Sender: TObject);
var xx,yy: Integer; //local variables
begin
        for xx:=0 to 29 do
                for yy:=0 to 39 do
                        begin
                             Images[xx,yy]:=Timage.Create(Form1);
                             Images[xx,yy].Canvas.Rectangle(0,0,17,17);
                             Images[xx,yy].Left:=xx*16;
                             Images[xx,yy].Top:=yy*16;
                        end;
end;

end.

我总是会收到这个错误:"Project Project1.exe has raised the exception class EClassNotFound with message "TImage not found". Process stopped. Use step or run to continue"
我尝试了互联网上的其他代码,例如:
Delphi: TImage.Create causes Access violation
http://www.delphi-central.com/tutorials/memory_game_2.aspx
但是都没有起作用!为什么会发生这种情况呢?
谢谢。

当您创建图像时,请使用TImage.Create(Self)。永远不要使用表单变量作为引用。 - LU RD
1
@TLama,假设您正在使用具有本地变量TForm1的过程创建表单。会发生什么?图像将绑定到全局Form1参数,这不是一个好的实践。事实上非常糟糕。Images变量应在表单类中声明。 - LU RD
@TLama,另一个问题是,如果你在代码中动态创建TForm1的实例并将其分配给不同名称的变量,那么你会遇到麻烦。例如:var TheForm: TForm1;begin TheForm := TForm1.Create(nil); try TheForm.ShowModal; finally TheForm.Free; end;。如果在构造TheForm时,如果没有已经创建Form1的实例,你会得到一个AV错误。始终使用Self,它将引用对象的当前实例 - Ken White
2个回答

8

您确定在使用TImage.Create函数的那一行代码处出现了异常吗?是否存在一个包含TImage实例但未在TForm1声明中的无效DFM文件?

通常,表单或数据模块中使用的所有子类都会自动进行流式处理注册。由于在该表单中没有声明TImage,且该应用程序的其他表单中也没有TImage,因此没有进行注册。

您可以通过在表单上放置TImage来简单测试。


1
打开你的表单 (f12)。右键点击: "以文本形式查看"。找到这一行:" object Image1: TImage"。删除该行及其下面所有包括下一个end的行。按F9。 - Pieter B

1

如果你想在表格中显示,请将此代码添加到循环中:

Images[xx,yy].Parent:= Self;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接