1

へー!プログラムで TShape を作成しようとしています。プログラムを実行してボタンをクリックすると、すべてが機能します。しかし、もう一度ボタンをクリックすると、イベント OnMouseEnter(OnMouseLeave) は LAST Shape でのみ機能します。以前のものでは動作しません。

    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含まてい ます(ところで、最初の を作成する前にインクリメントしているため、 m にデータを入力していません)。Shape[]i TShapeShape[0]iTShape

あなたが試みていることを行うには、イベントハンドラーは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 に答える