Building Your First Custom Lazarus Component - A Step-by-Step Guide

User:Aruna.Hewapathirane

TODO: THIS IS A WORK IN PROGRESS SO EXPECT A MESS UNTIL PEER REVIEWED AND FINALIZED!
Please do not link to this page yet, as it's name may be changed

Explain:

TSimpleLED – A Minimal Custom LED Indicator Component for Lazarus

This code is a teaching/learning example of building your own visual component in Lazarus/Free Pascal — specifically a small LED indicator control that changes color based on its state.

Teaching Points Demonstrated

In short: This example teaches the basic workflow for creating, drawing, and registering a custom visual component in Lazarus — an ideal beginner’s project to learn component creation, custom painting, and property handling.

unit SimpleLED;

{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils, Controls, Graphics, Math;

type
  TLEDState = (ledOff, ledOn, ledWarning, ledError);

  TSimpleLED = class(TCustomControl)
  private
    FState: TLEDState;
    procedure SetState(AValue: TLEDState);
  protected
    procedure Paint; override;
  public
    constructor Create(AOwner: TComponent); override;
  published
    property State: TLEDState read FState write SetState default ledOff;
    property Align;
    property Anchors;
    property Visible;
    property Enabled;
  end;

procedure Register;

implementation

procedure Register;
begin
  RegisterComponents('Samples', [TSimpleLED]);
end;

constructor TSimpleLED.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  Width := 30;
  Height := 30;
  FState := ledOff;
end;

procedure TSimpleLED.SetState(AValue: TLEDState);
begin
  if FState = AValue then Exit;
  FState := AValue;
  Invalidate;  // triggers repaint
end;

procedure TSimpleLED.Paint;
var
  LEDColor: TColor;
  R: TRect;
  CenterX, CenterY, Radius: Integer;
begin
  inherited Paint;

  // Decide LED color based on state
  case FState of
    ledOff: LEDColor := clGray;
    ledOn: LEDColor := clLime;      // bright green
    ledWarning: LEDColor := clYellow;
    ledError: LEDColor := clRed;
  else
    LEDColor := clGray;
  end;

  // Clear background
  Canvas.Brush.Color := Self.Color;
  Canvas.FillRect(ClientRect);

  // Draw a filled circle in center
  R := ClientRect;
  CenterX := (R.Left + R.Right) div 2;
  CenterY := (R.Top + R.Bottom) div 2;
  Radius := Min(Width, Height) div 2 - 2;

  // Draw shadow for 3D effect
  Canvas.Pen.Color := clBlack;
  Canvas.Brush.Color := LEDColor;
  Canvas.Ellipse(CenterX - Radius, CenterY - Radius, CenterX + Radius, CenterY + Radius);

  // Optional: small highlight circle for shine effect
  Canvas.Brush.Color := clWhite;
  Canvas.Pen.Color := clWhite;
  Canvas.Ellipse(CenterX - Radius div 3, CenterY - Radius div 3, CenterX - Radius div 5, CenterY - Radius div 5);
end;
end.

The code above each line explained and heavily commented