Step 2 - Implement a Property to Specify the Number of Sides

From RAD Studio
Jump to: navigation, search

Go Up to Creating a FireMonkey Primitive Control


The TRegularPolygon component needs to define the number of sides as a property so that component users can specify it. To implement a property (named NumbersOfSides), add the following line to the published section of the TRegularPolygon class:

property NumberOfSides: Integer;

Also, add a definition of the constructor to the public section as follows:

constructor Create(AOwner: TComponent); override;

So the code should look like this:

type
  TRegularPolygon = class(TShape)
  private
    { Private declarations }
  protected
    { Protected declarations }
  public
    { Public declarations }
    constructor Create(AOwner: TComponent); override;
  published
    { Published declarations }
    property NumberOfSides: Integer;
  end;

After you insert these lines, press CTRL+SHIFT+C. The IDE automatically adds the setter for the NumberOfSides property, and a skeleton for the constructor. The code now should look like this:

TRegularPolygon = class(TShape)
private
  FNumberOfSides: Integer;
  procedure SetNumberOfSides(const Value: Integer);
  { Private declarations }
protected
  { Protected declarations }
public
  { Public declarations }
  constructor Create(AOwner: TComponent); override;
published
  { Published declarations }
  property NumberOfSides: Integer read FNumberOfSides write SetNumberOfSides;
end;

constructor TRegularPolygon.Create(AOwner: TComponent);
begin
  inherited;

end;

procedure TRegularPolygon.SetNumberOfSides(const Value: Integer);
begin
  FNumberOfSides := Value;
end;

As with every polygon, the number of sides should be at least 3. So change the implementation of the SetNumberOfSides method as follows:

procedure TRegularPolygon.SetNumberOfSides(const Value: Integer);
begin
  if (FNumberOfSides <> Value) and (Value >= 3) then
  begin
    FNumberOfSides := Value;
    Repaint;
  end;
end;

The Repaint method tells the FireMonkey framework that this component needs to be repainted when the number of sides changes. In the constructor, you need to initialize the value of FNumbersOfSides field to make it a minimum of 3. By changing the field (instead of a property) you avoid unnecessary calls to the repaint method. Add the following code to the constructor:

constructor TRegularPolygon.Create(AOwner: TComponent);
begin
  inherited;
  FNumberOfSides := 3;
end;

Previous

Next