1

嘿!我正在尝试以编程方式创建一个 TShape。当我运行程序并单击按钮时 - 一切正常。但是当我再次单击该按钮时,事件 OnMouseEnter(OnMouseLeave) 仅适用于最后一个形状。不适用于以前的任何一个。

    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;
}
4

1 回答 1

2

您的OnMouse...事件处理程序i用于索引Shape[]数组,但i包含您创建的最后一个 TShape索引 (顺便说一句,您没有填充Shape[0]m 因为您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;
}
于 2015-03-31T19:39:35.197 回答