Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Timer/actionPerformed confusion

 
Malcolm Whitely
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hello everyone,
I hope someone can help me as I am very confused with a project that I am trying to complete. Basically, I need to move a shape from the left of the screen to the right. Here is my basic algorithm:
1. Paint circle in position x=0,y=0
2. After 1s has passed increment x (using timer/actionPerformed)
3. repaint
Unfortunately, x does not seem to be incrementing at all. Here is my code:

Any help would be greatly appreciated
Thanks.
[ February 06, 2003: Message edited by: Malcolm Whitely ]
 
Michael Morris
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Malcom,
Your problem is in the line:

x is never changing. You probably meant to just say x++. The postfix increment operator returns the value of its operand prior to incrementing it. So if x = 10 then it still equals 10 after the above line of code (even though for a split second it was 11). On the other hand, if you had used the prefix incrementer instead it would have worked, although it is redundant to have an expression like x = ++x, when you can just say ++x.
Hope this helps,
Michael Morris
 
Malcolm Whitely
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot Michael for your reply. It worked great! I do have a quick question though about the logic involved. Shouldn't x++ and ++x both increment the value of x?
Hope you can help me out with this?
Thanks again for your prompt reply.
 
Michael Morris
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Malcom,
Yes, they both increment x but as I explained in the previous post they differ in their return value: prefix returns the value after incrementing and postfix the value before incrementing. Why do you need both? For expressions like:
while (++x < 10) or while (x++ < 10)
The second while statement will evaluate true one more time (assuming that x starts out less than or equal to 10) than the first.
Hope this clears it up,
Michael Morris
 
Malcolm Whitely
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I see All is clear now. I'm currently trying to make the circle bounce back in the other direction. If I need any help I'll be sure to post back.
You've been a great help.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic