2015-03-31 56 views
0

Hej!我試圖以編程方式創建TShape。當我運行程序並單擊按鈕時 - 一切正常。但是當我再次點擊按鈕時,事件OnMouseEnter(OnMouseLeave)只能與最後一個形狀一起使用。不適用於任何以前的。C++ Builder,TShapes,如何更改顏色OnMouseEnter

int i=0; 
    TShape* Shape[50]; 
    void __fastcall TForm1::Button1Click(TObject *Sender) 
{ 
    int aHeight = rand() % 101 + 90; 
    int bWidth = rand() % 101 + 50; 
    i++; 
    Shape[i] = new TShape(Form1); 
    Shape[i]->Parent = this; 
    Shape[i]->Visible = true; 
    Shape[i]->Brush->Style=stCircle; 
    Shape[i]->Brush->Color=clBlack; 

    Shape[i]->Top = aHeight; 
    Shape[i]->Left = bWidth; 
    Shape[i]->Height=aHeight; 
    Shape[i]->Width=bWidth; 

    Shape[i]->OnMouseEnter = MouseEnter; 
    Shape[i]->OnMouseLeave = MouseLeave; 

    Label2->Caption=i; 


    void __fastcall TForm1::MouseEnter(TObject *Sender) 
{ 
    Shape[i]->Pen->Color = clBlue; 
    Shape[i]->Brush->Style=stSquare; 
    Shape[i]->Brush->Color=clRed; 
} 



void __fastcall TForm1::MouseLeave(TObject *Sender) 
{ 
    Shape[i]->Pen->Color = clBlack; 
    Shape[i]->Brush->Style=stCircle; 
    Shape[i]->Brush->Color=clBlack; 
} 

回答

1

OnMouse...事件處理程序使用i索引到Shape[]陣列,但i包含的指數最後TShape你創建(BTW,你是不是填充Shape[0]米因爲您之前遞增i創建第一個TShape)。

要你嘗試,事件處理程序需要使用他們Sender參數知道哪些TShape目前觸發每個事件,比如什麼:

TShape* Shape[50]; 
int i = 0; 

void __fastcall TForm1::Button1Click(TObject *Sender) 
{ 
    ... 

    Shape[i] = new TShape(this); 
    Shape[i]->Parent = this; 
    ... 
    Shape[i]->OnMouseEnter = MouseEnter; 
    Shape[i]->OnMouseLeave = MouseLeave; 

    ++i; 
    Label2->Caption = i; 
} 

void __fastcall TForm1::MouseEnter(TObject *Sender) 
{ 
    TShape *pShape = static_cast<TShape*>(Sender); 

    pShape->Pen->Color = clBlue; 
    pShape->Brush->Style = stSquare; 
    pShape->Brush->Color = clRed; 
} 

void __fastcall TForm1::MouseLeave(TObject *Sender) 
{ 
    TShape *pShape = static_cast<TShape*>(Sender); 

    pShape->Pen->Color = clBlack; 
    pShape->Brush->Style = stCircle; 
    pShape->Brush->Color = clBlack; 
}