Search code examples
delphidelphi-xe2delphi-xe

Create Frame depending on the purpose of the button


On the form:
* TCategoryButtons (for example, there are 3 categories in each of which 10 buttons)
* TPageControl (clean)
Created 30 (for example) different frames.

It is necessary when pressing the button:
1. Check whether a frame has already been created (only one frame for one button).
2. Create a tab in TPageControl and activate it.
3. Create a frame corresponding to the button and put it into the created tab (if the tab is closed, kill it and the frame).

That's what I could do:

procedure TForm1.CategoryButtons1Categories0Items0Click(Sender: TObject);
var
  Client: TTabSheet;
begin
  if (not Assigned(Frame2)) then
  begin
    Client := TTabSheet.Create(Self);
    Client.PageControl := PageControl1;
    Client.Caption := CategoryButtons1.Categories[0].Items[0].Caption;
    PageControl1.ActivePage := Client;

    Frame2 := TFrame2.Create(nil);
    Frame2.Parent := Client;
  end;
end;

I tried to do it this way:

type
  TFrameClass = class of tframe; 

function GetFrClass(const aClassID: Integer): TFrameClass;
begin
  case aClassID of
    1:
      Result := TFrame2;
    2:
      Result := TFrame3;
  else
    Result := nil;
  end;
end;

procedure TForm1.CreateFrm(tags: Integer; NameTSh: string);
var
  FrClass: TFrameClass;
  Frame: tframe;
  Client: TTabSheet;
begin
  FrClass := GetFrameClass(tags);

  if (FrClass <> nil) then
  begin
    Client := TTabSheet.Create(Self);
    Client.PageControl := PageControl1;
    Client.Caption := NameTSh;

    Frame := FrClass.Create(Client);
    Frame.Parent := Client;
  end;
end;

But this method does not limit the number of frame instances created.

Please tell me the solution!


Solution

  • You can use the tags: Integer value in procedure TForm1.CreateFrm() to determine whether a frame already exists in PageControl1 or not.

    Before you create a frame and add it to the PageControl1, check if any of the existing pages already has the value of tags in the tag property:

    procedure TForm1.CreateFrm(tags: Integer; NameTSh: string);
    var
      i: integer;
      ...
    begin
      for i := 0 to PageControl1.PageCount-1 do
        if PageControl1.Pages[i].tag = tags then
          Exit;
    
      FrClass := GetFrameClass(tags);
      ...
    

    At the end of the CreateFrm() procedure you store tags

      PageControl1.Pages[PageControl1.PageCount-1].Tag := tags;
    end;