Reputation: 65
I have problem with creating button with Image and Label inside it. Here my code:
Class:
type
Folder = class(TButton)
AName:TLabel;
AImage:TImage;
constructor Create(Nme:String;Path:String;Handle:TForm);
end;
Constructor:
constructor Folder.Create(Nme:String;Path:String;Handle:TForm);
begin
AImage:=Timage.Create(Self);
AName:=TLabel.Create(Self);
AImage.Parent:=Self;
AName.Parent:=Self;
AName.Caption:=Nme;
AImage.Picture.LoadFromFile(Path);
end;`
And event where I create this button:
procedure TForm3.Button1Click(Sender: TObject);
var Fld:Folder;
begin
Fld:=Folder.Create('It','D:\image.bmp',Form3);
Fld.Parent:=Form3;
Fld.Width:=100;
Fld.Height:=100;
end;
But when I'm creating this button it causes acess violation!What I must to do with it?
Upvotes: 1
Views: 3045
Reputation: 5438
The problem is that you have declared a customized version of constructor, but you are not calling the parent constructor of TButton
class.
You need to change the constructor like this:
constructor Folder.Create(Nme: String; Path: String; Handle: TForm);
begin
inherited Create(Handle); // <- Add this line
AImage := TImage.Create(Self);
AName := TLabel.Create(Self);
AImage.Parent := Self;
AName.Parent := Self;
AName.Caption := Nme;
AImage.Picture.LoadFromFile(Path);
end;
You need to learn how to debug such problems yourself.
Put a breakpoint on line Fld:=Folder.Create('It','D:\image.bmp',Form3);
and use Step Over
F8 / Trace Into
F7 from Run
menu to check your code line by line.
You will see that once you reach the line AImage.Parent:=Self;
the exception occurs. This is because Self
, which points to your Folder
object, was not initialized correctly, and is not a proper TButton
descendant.
You need to learn how to do that to progress any further with Delphi, and you will very soon be able to solve such problems yourself.
Also if you need to write a custom component for Delphi, invest some time learning more about the way components work and are being used. I would recommend the following guides on component writing:
Also consult a guide on Delphi Coding Style.
At first glance:
T
F
instead of A
constructor
should be in public section and fields in private
or protected
Upvotes: 9