Show: Delphi C++
Display Preferences

Step 3 - Using TTimer to Refresh TClockLabel Every Second

From RAD Studio
Jump to: navigation, search

Go Up to Creating a Styled FireMonkey Component by Extending an Existing Component


To refresh TClockLabel every second, this tutorial uses the TTimer component internally. To use the TTimer component within the TClockLabel component, you need to:

  • Create an instance of TTimer in the constructor of TClockLabel.
  • Configure the TTimer component to fire the OnTimer event every second.
  • Update the Text property when the OnTimer event is fired.
  • Destroy the instance of TTimer in the destructor of TClockLabel.

To do these things, define the following additional members (members previously created are not listed here):

In Delphi:

type
TClockLabel = class(TLabel)
private
  FTimer: TTimer;
  procedure OnTimer(Sender: TObject);
public
  destructor Destroy; override;
end;

In C++:

class PACKAGE TClockLabel : public TLabel {
private:

	TTimer* FTimer;

	void __fastcall OnTimer(TObject* Sender);

public:
	__fastcall ~TClockLabel(void);
};

Just as in previous steps, pressing CTRL+SHIFT+C creates placeholders for these methods. Implement these methods as follows:

In Delphi:

constructor TClockLabel.Create(AOwner: TComponent);
begin
  FFormat := 'c';
  inherited;

  // No need to use TTimercompoment at design time.
  if not (csDesigning in ComponentState) then
  begin
    FTimer := TTimer.Create(AOwner);
    FTimer.OnTimer := OnTimer;
    FTimer.Interval := 1000;
    FTimer.Enabled := True;
  end;

  UpdateLabel;
end;

destructor TClockLabel.Destroy;
begin
  FreeAndNil(FTimer);
  inherited;
end;

procedure TClockLabel.OnTimer(Sender: TObject);
begin
  UpdateLabel;
end;

In C++:

__fastcall TClockLabel::TClockLabel(TComponent* Owner) : TLabel(Owner) {

	FFormat = 'c';

	FTimer = new TTimer(Owner);
	FTimer->OnTimer = OnTimer;
	FTimer->Interval = 1000;
	FTimer->Enabled = true;

	UpdateLabel();
}

__fastcall TClockLabel::~TClockLabel() {
	FreeAndNil(FTimer);
}

void __fastcall TClockLabel::OnTimer(TObject* Sender) {
	UpdateLabel();
}

As you might notice, the created instance of TTimer depends on the ComponentState property. This is because you do not have to refresh the Label at design time (while it runs in the IDE). This restricts creation of TTimer component only at running component outside of the IDE (as a standard application).

Now the TClockLabel component is implemented. In the Project Manager, right-click the TClockLabel.bpl package and select Build from the context menu. Then select Install to install the developed component package and to register the component:

ClockLabeIContextMenu.png

Now you can see the new behavior of the TClockLabel component in the Form Designer.

Previous

Next

Personal tools
In other languages
Previous Versions
Assistance