Reputation: 1280
So I am nearing the end of my tasks in this particular set... I am trying to make an ellipse be drawn every time the timer ticks over. The timer has been enabled by default and the interval for each timer tick is 100ms. When I run the debugging, one ellipse is drawn on the canvas and no more - I have already tried a for-loop and a while-loop to set an arbitrary amount of ellipses to be drawn on each timer tick but that didn't work. Ideally I would like to create buttons that turn the timer on and off (I have a few ideas on how to do this, thanks to an earlier problem that was solved), I would like to get the code for the timer right first. Below is the code I have managed to get so far:
private: System::Void timer1_Tick(System::Object^ sender, System::EventArgs^ e)
{
Random^ rGen;
timer1->Enabled = true;
Graphics^ mainCanvas = CreateGraphics();
// while loop to set upper limit for no# of ellipses
// note: this is just for testing - would like to have
// ellipses drawn automatically at random etc.
int i = 0;
while(i < 20)
{
rGen = gcnew Random();
Brush^ greenBrush = gcnew SolidBrush(Color::Green);
static int randX = rGen->Next(Width); //random x co-ordinate
static int randY = rGen->Next(Height); //random y co-ordinate
static int randWidth = rGen->Next(100); //random ellipse width
static int randHeight = rGen->Next(100); //random ellipse height
mainCanvas->FillEllipse(greenBrush, randX,randY,randWidth,randHeight);
i++;
}
}
I am probably missing only one or two crucial things, I have also been learning C# and ASP.NET at the same time so my heads nearly exploding with so much being crammed into it. Any help is appreciated :).
Upvotes: 1
Views: 591
Reputation: 345
Just a quick hint, make sure to enable the timer outside of this method, you might of already done that but it's impossible to see here, this ensures that you actually enter the method. As @Hans said, remove the statics.
Upvotes: 0
Reputation: 942468
static int randX = rGen->Next(Width);
The static keyword is your nemesis here. When used before a local variable, it ensures that the variable is initialized only once. So you only ever draw the exact same ellipse. Easy to see when you use the debugger btw.
Upvotes: 2