Setting Owned Classes' Properties

From RAD Studio
Jump to: navigation, search

Go Up to Publishing the Pen and Brush


As the final step in handling the pen and brush classes, you need to make sure that changes in the pen and brush cause the shape control to repaint itself. Both pen and brush classes have OnChange events, so you can create a method in the shape control and point both OnChange events to it.

Add the following method to the shape control, and update the component's constructor to set the pen and brush events to the new method:

type
  TSampleShape = class(TGraphicControl)
  published
    procedure StyleChanged(Sender: TObject);
  end;
.
.
.
implementation
.
.
.
constructor TSampleShape.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);                      { always call the inherited constructor }
  Width := 65;
  Height := 65;
  FPen := TPen.Create;                                               { construct the pen }
  FPen.OnChange := StyleChanged;                       { assign method to OnChange event }
  FBrush := TBrush.Create;                                         { construct the brush }
  FBrush.OnChange := StyleChanged;                     { assign method to OnChange event }
end;
procedure TSampleShape.StyleChanged(Sender: TObject);
begin
  Invalidate;                                    { erase and repaint the component }
end;


//header file
class PACKAGE TSampleShape : public TGraphicControl
{
  .
  .
  .
public:
    void __fastcall StyleChanged(TObject* Owner);
    .
    .
    .
};


//implmentation file
__fastcall TSampleShape::TSampleShape(TComponent* Owner) : TGraphicControl(Owner)
{
  Width = 65;
  Height = 65;
  FBrush = new TBrush();
  FBrush->OnChange = StyleChanged;
  FPen = new TPen();
  FPen->OnChange = StyleChanged;
}


//also include StyleChanged method in the implementation file
void __fastcall TSampleShape::StyleChanged( TObject* Sender)
{
  Invalidate();         // repaints the component
}

With these changes, the component redraws to reflect changes to either the pen or the brush.

See Also