Dynamically creating TLabel components

Posted by Johan p14205 on April 14, 2007

In Reply to String Handling: Seperating Characters posted by Brendan on April 02, 2007

I need take each character in a string and assign it to a label. I don't have the exact code i wrote cause it's at school... It didn't work. But from memory, I wrote something like this:

var
  word: string;
  j: integer;
  letter: array [1..15] of string;
begin
  word := 'DELPHI';
  for j := 1 to length(word) do
    begin
    letter[j]:=copy(word,j,1);

and i've assigned each letter in the array to a different label on the formcreate procedure...

For each character of the "word", you have to create a TLabel component. By the way, you'd better not name it as "word" in your code, because WORD is a reserved word :) in Delphi, so let's call it "TheWord".

The Owner as well as the Parent of each new label must be the form; that's what "self" stands for in the code below.

Label.Top and Label.Left are the coordinates. And finally, you set Label.Caption to what you want to display in each label. It's not necessary to create an extra array for this, because the string TheWord is already an "array of characters".

procedure TForm1.FormCreate(Sender: TObject);
const
  TheWord = 'DELPHI';
var
  I: integer;
  NewLabel: TLabel;
begin
  for I := 1 to Length(TheWord) do begin
    NewLabel := TLabel.Create(self);
    NewLabel.Parent := self;
    NewLabel.Top := 20;
    NewLabel.Left := I * 20;
    NewLabel.Caption := TheWord[I];
  end;
end;     

Related articles

       

Follow Ups