TSimpleBox with Color property

This is an old revision of TSimpleBox with Color property, edited by Aruna.Hewapathirane at . The current revision is 150311.

<syntaxhighlight lang=pascal>

unit SimpleBox;

{$mode objfpc}{$H+}

interface

uses

 Classes, SysUtils, Controls, Graphics;

type

 TSimpleBox = class(TGraphicControl)
 private
   FColor: TColor;          // field to store the property value
   procedure SetColor(AValue: TColor);
 protected
   procedure Paint; override;
 public
   constructor Create(AOwner: TComponent); override;
 published
   property Color: TColor read FColor write SetColor default clRed;
 end;

procedure Register;

implementation

procedure Register; begin

 RegisterComponents('Samples', [TSimpleBox]); // IDE "Samples" tab

end;

constructor TSimpleBox.Create(AOwner: TComponent); begin

 inherited Create(AOwner);
 Width := 50;
 Height := 50;
 FColor := clRed;  // default color

end;

procedure TSimpleBox.SetColor(AValue: TColor); begin

 if FColor <> AValue then
 begin
   FColor := AValue;
   Invalidate;  // trigger repaint
 end;

end;

procedure TSimpleBox.Paint; begin

 Canvas.Brush.Color := FColor;
 Canvas.FillRect(ClientRect);

end;

end. <syntaxhighlight lang=pascal>

What’s New in Step 2

Field + Property FColor: TColor; property Color: TColor read FColor write SetColor default clRed; The field stores the actual data.

The property exposes it to the Object Inspector.

default clRed tells Lazarus the starting value.

Setter Method

procedure SetColor(AValue: TColor); Updates the field and calls Invalidate so the control repaints.

published Section

Any property declared here shows up in Lazarus’s Object Inspector.

Teaching tip: With this, a newbie can drop the control on a form, change its Color in the Object Inspector, and see the effect immediately.