i am using drawImage() function and increasing the X value so that it appears as though the image is scrolling (similar to marquee tag) But the code isn't working. The X values are increased but still the image is getting drawn at the same place again and again. Please tell me why is this happening?
Silly me! yeah i forgot to initialise the width itself. But what do you mean by thread synchronization? in this case no objects are shared between threads and moreover only 1 thread is there so why to synchronize?
Also what should i synchronize?
will this snippet work?
Is this the correct way of doing it?
author and iconoclast
There are two threads both accessing the variable "x": the one that you created that increments "x", and the AWT event thread that paints the window, which reads it and uses it to position the image. In theory, any time you write a variable in one thread and read it from another, those access must explicitly be synchronized, or the variable must be marked "volatile"; otherwise, it's possible for one or both threads to cache thread-local values of the variable, so that the changes made by the one thread will not be seen by the other. In practice, you can often get away without synchronization; but on a different machine (for example, a multicore or multiprocessor machine) or a different JVM implementation, you might not.
In this case, the easiest thing to do is mark "x" volatile: