【问题标题】:C++ Builder, TShapes, How to change color OnMouseEnterC++ Builder, TShapes, 如何改变颜色 OnMouseEnter
【发布时间】:2015-03-31 12:08:32
【问题描述】:

嘿嘿!我正在尝试以编程方式创建一个 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;
}

【问题讨论】:

    标签: c++ c++builder onmouseover c++builder-xe7


    【解决方案1】:

    您的OnMouse... 事件处理程序正在使用i 来索引Shape[] 数组,但i 包含您创建的最后一个 TShape 的索引(顺便说一句,您没有填充Shape[0]m,因为您在创建第一个TShape之前递增i)。

    要执行您正在尝试的操作,事件处理程序需要使用其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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-22
      • 2011-11-22
      • 1970-01-01
      • 2014-04-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多