TSimpleBox with Color + Caption

This is an old revision of TSimpleBox with Color + Caption, edited by Aruna.Hewapathirane at . The current revision is 150317.

Alright — here’s Step 2 of our beginner-friendly Lazarus custom component:

We’ll take our TSimpleBox and give it a Color property that shows up in the Object Inspector.

This teaches:

  1. How to declare a published property
  2. How to store it in a field
  3. How to repaint when it changes

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

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.