i try to move it to the right(x++) every seconds
i try to move it with thread..
If you put that part of the constructor in a thread, then you can call thread.sleep(1000);
(1000 milliseconds for a 1 second delay) and then refresh, which should move the target across the screen.
Help
A new Thread
is created like this:
Thread t = new Thread(new Runnable() {
@Override
public void run() {
//work here
}
});
t.start();//start thread
however I'd suggest a Swing Timer
as it runs on EDT
:
EDIT:
As per your questions I suggest using a Timer
the creating thread point was for general knowledge.
The probelm is the Thread is not run on EDT Thread of your swing GUI where as a Timer
does:
int delay = 1000; //milliseconds
ActionListener taskPerformer = new ActionListener() {
int count=0;
public void actionPerformed(ActionEvent evt) {
if(count==10) {//we did the task 10 times
((Timer)evt.getSource()).stop();
}
label.setLocation((label.getLocationOnScreen().x+10), label.getLocationOnScreen().y);
System.out.println(SwingUtilities.isEventDispatchThread());
count++;
}
};
new Timer(delay, taskPerformer).start();
Reference:
Here is an Swing
example of a simple puzzle game.
Java Swing Shuffle Game
When you press Pause
button the title will get animate until you release the pause. Similarly you can use it for JLabel
. Source code is also attached.
Hope that can help you much.