2

我以 VBto 为起点,并大量学习了 Delphi 6 User's Guide。我可以编译我的新组件,但我想不出办法让它显示,所以我可以完成调试它。50 年的编程经验也无济于事。这是我的组件的内容:

type 

 TChangeEvent = procedure(Sender: TObject; v: String) of object;
 TTxtSpnr = class(TWinControl)
   Lbl: TLabel;
   Txt: TEdit;
   Scrll:   TScrollBar;
 private
   FonChange: TChangeEvent;
   busy, tweaked: Boolean;
   NewValue: String;
 protected
   procedure Changed(v: String); dynamic;
   property onChange: TChangeEvent read FonChange write FOnChange;
   procedure ScrllChange(Sender: TObject);
   procedure ScrllScroll(Sender: TObject; ScrollCode: TScrollCode; var ScrollPos: Integer);
   procedure TxtEnter(Sender: TObject);
   procedure TxtKeyUp(Sender: TObject; var Key: WORD; Shift: TShiftState);
   procedure TxtExit(Sender: TObject);
   procedure Txt_Validate(var Cancel: Boolean);
 public
   function GetCaption(): String;
   procedure SetCaption(New_Caption: String);
   function GetMax(): Smallint;
   procedure SetMax(New_Max: Smallint);
   function MaxOf(a: Double; B: Longint): OleVariant;
   function MinOf(a: OleVariant; B: Longint): OleVariant;
   function GetMin(): Smallint;
   procedure SetMin(New_Min: Smallint);
   function GetText(): String;
   procedure SetText(New_Text: String);
   constructor Create(AOwner: TComponent); override;
   destructor Destroy; override;
 published
   property Caption: String read GetCaption write SetCaption;
   property Enabled: Boolean read GetEnabled write SetEnabled;
   property Max: Smallint read GetMax write SetMax;
   property Min: Smallint read GetMin write SetMin;
   property Text: String read GetText write SetText;
 end;
var 
 TxtSpnr: TTxtSpnr;
implementation 

uses Math; 
{$R *.dfm} 

procedure TTxtSpnr.Changed(V: String); begin 

 if assigned(FonChange) then FonChange(self,V);
end; 

constructor TTxtSpnr.Create(AOwner: TComponent); begin 

 inherited Create(AOwner);
 Lbl := TLabel.Create(Self);
 with Lbl do begin
   Parent := Self;
 end;
 Txt := TEdit.Create(Self);
 with Txt do begin
   Parent := Self;
 end;
 Scrll := TScrollBar(Self);
 with Scrll do begin
   Parent := Self;
 end;
end; 

这是测试驱动程序:

type 

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

 Form1: TForm1;
implementation 

{$R *.dfm} 

procedure TForm1.FormCreate(Sender: TObject); begin 

 FTxtSpnr := TTxtSpnr.create(Self);
 with FTxtSpnr do begin
   Left:=10;
   Top:=10;
   Visible:=true;
   Show;
 end;
end; 

但它不会编译并在构造函数中说“一个对象不能是它自己的父对象”。取出父设置,它编译但不显示组件。我错过了什么?

4

1 回答 1

4

第一的,

Scrll := TScrollBar(Self);

当然应该阅读

Scrll := TScrollBar.Create(Self);

第二,

FTxtSpnr := TTxtSpnr.create(Self);
with FTxtSpnr do begin
  Left:=10;
  Top:=10;
  Visible:=true;
  Show;
end;

应该

FTxtSpnr := TTxtSpnr.create(Self);
with FTxtSpnr do
begin
  Parent := Self;
  Left := 10;
  Top := 10;
end;

你忘了设置父级。

另外,全局变量

var 
  TxtSpnr: TTxtSpnr;

看起来很危险。如果您不知道添加这两行的确切原因,您可能应该删除它们。

于 2013-07-31T22:28:40.707 回答