作为一种自学练习,我制作了一个包含6个面板的2x3矩形表格,我希望它们可以在一个接一个的可见和不可见之间切换.我试图通过使用某种类型的for循环来实现.我当然可以这样写:
Panel1.Visible := true;
Panel1.Visible := false;
Panel2.Visible := true;
Panel2.Visible := false;
Panel3.Visible := true;
etc. etc.
Run Code Online (Sandbox Code Playgroud)
但是当我决定我希望它在每一步之间等待100毫秒时,这需要相当多的打字并且效率非常低.例如,我必须编辑所有六个步骤才能等待.这可以用于六个步骤,但也许另一次我想要做一百次!所以我认为还必须有一种方法来使用for循环,其中变量从1到6变化并用于对象标识符.所以它会是这样的:
for variable := 1 to 6 do begin
Panel + variable.Visible := true;
Panel + variable.Visible := false;
end;
Run Code Online (Sandbox Code Playgroud)
现在,这显然不起作用,但我希望这里有人可以告诉我这是否有可能,如果是,如何.也许我可以使用字符串作为标识符?我的解释可能非常糟糕,因为我不知道所有技术术语,但我希望代码解释一些东西.
Ken*_*ite 18
您可以遍历面板的所有者Components阵列.
var
i: Integer;
TmpPanel: TPanel;
begin
{ This example loops through all of the components on the form, and toggles the
Visible property of each panel to the value that is opposite of what it has (IOW,
if it's True it's switched to False, if it's False it's switched to True). }
for i := 0 to ComponentCount - 1 do
if Components[i] is TPanel then
begin
TmpPanel := TPanel(Components[i]);
TmpPanel.Visible := not TmpPanel.Visible; // Toggles between true and false
end;
end;
Run Code Online (Sandbox Code Playgroud)
FindComponent如果您希望按名称使用非常特定类型的组件,也可以使用该方法.例如,如果您有6个面板,并且它们的名称是Panel1,Panel2等等:
var
i: Integer;
TmpPanel: TPanel;
begin
for i := 1 to 6 do
begin
TmpPanel := FindComponent('Panel' + IntToStr(i)) as TPanel;
if TmpPanel <> nil then // We found it
TmpPanel.Visible := not TmpPanel.Visible;
end;
end;
Run Code Online (Sandbox Code Playgroud)
在这种情况下,您希望在运行时而不是在设计时动态创建控件.试图解决6个不同的变量只是一个痛苦的世界.当你需要网格为3x4而不是2x3时,你会更加后悔这个决定.
所以,从一个完全空白的表格开始.并在代码中添加一个二维面板数组:
private
FPanels: array of array of TPanel;
Run Code Online (Sandbox Code Playgroud)
然后,在窗体的构造函数或OnCreate事件处理程序中,您可以通过调用如下函数来初始化数组:
procedure TMyForm.InitialisePanels(RowCount, ColCount: Integer);
var
Row, Col: Integer;
aLeft, aTop, aWidth, aHeight: Integer;
Panel: TPanel;
begin
SetLength(FPanels, RowCount, ColCount);
aTop := 0;
for Row := 0 to RowCount-1 do begin
aLeft := 0;
aHeight := (ClientHeight-aTop) div (RowCount-Row);
for Col := 0 to ColCount-1 do begin
Panel := TPanel.Create(Self);
FPanels[Row, Col] := Panel;
Panel.Parent := Self;
aWidth := (ClientWidth-aLeft) div (ColCount-Col);
Panel.SetBounds(aLeft, aTop, aWidth, aHeight);
inc(aLeft, aWidth);
end;
inc(aTop, aHeight);
end;
end;
Run Code Online (Sandbox Code Playgroud)
现在,您可以使用笛卡尔坐标而不是平面一维数组来引用您的面板.当然,如果需要,您也可以轻松地声明平面一维数组.
关键的想法是,当您在结构化布局中创建大量控件时,最好放弃设计器并使用代码(循环和数组).
使用FindComponent方法TComponent:
for variable := 1 to 6 do begin
pnl := FindComponent('Panel' + IntToStr(variable));
if pnl is TPanel then
begin
TPanel(pnl).Visible := true;
TPanel(pnl).Visible := false;
end;
end;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10070 次 |
| 最近记录: |