在运行时构造一个按钮

时间:2015-06-30 07:40:00

标签: 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;
  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

知道怎么解决吗?我查了错误但无济于事。

1 个答案:

答案 0 :(得分:4)

您尚未声明代码在内部执行的方法。在Object Inspector中找到表单的OnCreate事件,双击它并将代码放在IDE生成的事件处理程序存根中。

您还必须为按钮指定Parent。按钮成为表单类的成员会好得多。

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;