Delphi 在运行时构造按钮
我已经看过这个示例,但是由于错误,无法编译Delphi 在运行时构造按钮,delphi,Delphi,我已经看过这个示例,但是由于错误,无法编译 unit Unit2; interface uses Winapi.Windows,Winapi.Messages,System.SysUtils,System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type TForm2 = class(TForm) editType: TEdit;
unit Unit2;
interface
uses
Winapi.Windows,Winapi.Messages,System.SysUtils,System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type
TForm2 = class(TForm)
editType: TEdit;
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form2: TForm2;
RunTimeButton : TButton;
implementation
{$R *.dfm}
begin
{Self refers to the form}
RunTimeButton := TButton.Create(Self);
{Assign properties now}
RunTimeButton.Caption := 'Run-time';
RunTimeButton.Left := 20;
{Show the button}
RunTimeButton.Visible := True;
end;
end.
错误是:
[dcc32 Error] Unit2.pas(28): E2003 Undeclared identifier: 'Self'
[dcc32 Error] Unit2.pas(34): E2029 '.' expected but ';' found
知道怎么修吗?我已经查找了错误,但没有结果。您没有声明代码在内部执行的方法。在对象检查器中找到表单的OnCreate事件,双击它并将代码放入IDE生成的事件处理程序存根中 还必须为按钮指定父级。如果button是form类的成员,那就更好了
type
TForm2 = class(TForm)
editType: TEdit;
procedure FormCreate(Sender: TObject);
private
FRunTimeButton: TButton;
end;
var
Form2: TForm2;
implementation
{$R *.dfm}
procedure TForm2.FormCreate(Sender: TObject);
begin
FRunTimeButton := TButton.Create(Self);
FRunTimeButton.Parent := Self;
FRunTimeButton.Caption := 'Run-time';
FRunTimeButton.Left := 20;
end;
您不应该声明您必须声明的阅读或类似内容吗?在问问题时,OP似乎没有意识到Delphi不支持单元内的独立开始…结束块,这就是为什么他得到了“.”预期错误。实际上,在单元的实现部分可以有一个独立的开始-结束块,但用于单元初始化。它应该在代码的末尾,并在结尾处有一个句号。OP似乎不太理解TForm1是一个类,代码通常应该在方法中。新手倾向于将单元视为类,不知道带代码的表单只是单元中可以声明的众多内容之一。@RudyVelthuis:谢谢你,我知道,但是你的评论比我更能表达我的意思。