Delphi原創算法:動態創建30個按鈕,每行6個共5行,順序排列,顯示在ScrollBox上

procedure TForm1.Button1Click(Sender: TObject);
const
iHtoH = 20; //行間距
iWtoW = 10; //列間距
iPerLine = 6;//每行個數
iWidth = 80; //按鈕寬度
var
I : integer;
begin
//算法:動態創建30個按鈕,每行6個共5行,順序排列,顯示在ScrollBox上
for I := 1 to 30 do
    with TButton.Create(Self) do begin
      Name := 'Btn' + InttoStr(I);
      Parent := Self.ScrollBox1;
      Caption := Name;
      Top := iHtoH + (30+iHtoH) * (I div iPerLine - integer((I mod iPerLine)=0));
      Left := iWtoW + (iWidth+iWtoW) * ((I-1) mod iPerLine);
      Show;
    end;
end;//或許可以繼續精練一下

效果如下:

 

-------------------------------------------------------

 

http://topic.csdn.net/u/20080407/15/54206ece-4603-43df-b455-5f695d779ba5.html?seed=455055698

在CSDN解答問題後整理以下代碼:

const
iHtoH = 20; //行間距
iWtoW = 10; //列間距
iWidth = 80; //按鈕寬度
iCount = 30; //按鈕個數
var
iPerLine : integer;//每行個數
BtnArr : array[1..iCount] of TButton;

procedure TForm1.FormCreate(Sender: TObject);
var
I : integer;
begin
iPerLine := Self.ClientWidth div (iWidth+iWtoW);
for I := 1 to iCount do begin
    BtnArr[I] := TButton.Create(Self);
    with BtnArr[I] do begin
      Name := 'Btn' + InttoStr(I);
      Parent := Self;
      Caption := Name;
      Top := iHtoH + (30+iHtoH) * (I div iPerLine - integer((I mod iPerLine)=0));
      Left := iWtoW + (iWidth+iWtoW) * ((I-1) mod iPerLine);
      Show;
    end;
end;
end;

procedure TForm1.FormResize(Sender: TObject);
var
I : integer;
begin
iPerLine := Self.ClientWidth div (iWidth+iWtoW);
for I := 1 to iCount do
    with BtnArr[I] do begin
      Top := iHtoH + (30+iHtoH) * (I div iPerLine - integer((I mod iPerLine)=0));
      Left := iWtoW + (iWidth+iWtoW) * ((I-1) mod iPerLine);
    end;
end;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章