Wh1*_*Ck5 0 delphi runtime delphi-7 dynamicobject
好的,我正在尝试在TScrollBox表面上创建一些自定义数量的TPanel,就像你可以在下面的图像上看到的那样.

为了得到这个,我使用以下代码,并且工作正常.
var
pan: array of TPanel;
maxp, i, x, y: Integer;
...
maxp := 10;
SetLength(pan, maxp);
for i := 1 to maxp do begin
// x is correct value; doesn't cause problem
// y is correct value; doesn't cause problem
pan[i-1] := TPanel.Create(form1);
with pan[i-1] do begin
Width := 100;
Height := 150;
Top := x * 151;
Left := y * 101;
Parent := ScrollBox1;
end;
end;
Run Code Online (Sandbox Code Playgroud)
现在,我有问题将TImage对象放在每个具有相同索引的TPanel中(img [0] - > pan [0],img [1] - > pan [1]等).看下图:

使用相同的逻辑,我试图创建TImage,但没有成功.
我正在使用此代码,无法弄清楚是什么问题.它对我来说看起来很简单,但不知怎的,它没有提供预期的效果.
var
pan: array of TPanel;
img: array of TImage;
maxp, i, x, y: Integer;
...
maxp := 10;
SetLength(pan, maxp);
SetLength(img, maxp);
for i := 1 to maxp do begin
// x is correct value; doesn't cause problem
// y is correct value; doesn't cause problem
pan[i-1] := TPanel.Create(form1);
with pan[i-1] do begin
Width := 100;
Height := 150;
Top := x * 151;
Left := y * 101;
Parent := ScrollBox1;
end;
img[i-1] := TImage.Create(form1);
with img[i-1] do begin
Width := 98;
Left := 1;
Height := 148;
Top := 1;
// in original code next line had img[0]. which caused problem
Picture.LoadFromFile('some_image_file');
Parent := pan[i-1];
end;
end;
Run Code Online (Sandbox Code Playgroud)
不知何故,它将所有TImage对象放在第一个TPanel(pan [0])中的相同位置.这让我感到困惑,因为它说,Parent := pan[i-1];但由于某种原因,它总是把TImage放在pan [0].我尝试使用断点来查看每个for循环周期后发生了什么(最后添加了Application.ProcessMessages),它确实创建了10个不同的图像但是将它们放到了pan [0]上.当然,最后它显示加载到pan [0]中的最后一个图像.
我的问题是如何为每个动态TPanel制作一个动态TImage(具有相同的数组索引)?
解决了!
和建议 - 摆脱with块.起初它们看似无辜和简单,但从长远来看,它们只能编写难以排除故障的草率代码.如果您一直使用显式变量引用,那么首先就不会发生此问题.
var
Panels: array of TPanel;
Panel: TPanel;
Images: array of TImage;
Image: TImage;
maxp, i, x, y: Integer;
...
maxp := 10;
SetLength(Panels, maxp);
SetLength(Images, maxp);
for i := 1 to maxp do begin
Panel := TPanel.Create(form1);
Panels[i-1] := Panel;
Panel.Parent := ScrollBox1;
Panel.SetBounds(...);
Image := TImage.Create(form1);
Images[i-1] := Image;
Image.Parent := Panel;
Image.SetBounds(...);
Image.Picture.LoadFromFile('some_image_file');
end;
Run Code Online (Sandbox Code Playgroud)