TSimpleBox with Color property

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.

What’s New in Step 2

Field + Property

default clRed tells Lazarus the starting value.

Setter Method

published Section

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.