Reputation: 301
I'm using java swings for my application. Below is the piece of my code. However I know that Thread.sleep()
should not be used with swings. I read some posts that says to use Timer
from javax.swing.timer
But for the below code I do not know how to implement it.
public void mouseClicked(MouseEvent e) {
try{
demo.main("Welcome");
Thread.sleep(900);
demo.main("Argument to main");
Thread.sleep(900);
demo.main("Argument to main");
// after this I call a method say `xyz` which also uses Thread.sleep()
// and this `xyz` method uses variables that are updated in `demo.main()`
}catch(Exception e){
e.printStackTrace();
}
How can I implement the same behaviour as sleep?
EDIT:
demo.main()
doesnot update GUI, But xyz()
updates GUI depending
variables updated in demo.main()
demo.main()
at first when the mouse is clicked and after a minute I want to call it again and again after a minute. And after the completion of this I want to call another method xyz()
which also uses thread.sleep()
and uses variables updated in demo.main()
Upvotes: 0
Views: 487
Reputation: 65793
I would use a ScheduledExecutorService
and an ordered list of actions. Using enum
is good for this. This enum
could then implement a simple functional interface
.
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
enum ClickAction {
Action1(900) {
@Override
void execute() {
message("Welcome");
}
},
Action2(900) {
@Override
void execute() {
message("Another message");
}
};
private final int delayAfter;
private ClickAction(int delayAfter) {
this.delayAfter = delayAfter;
}
abstract void execute();
}
private static void message(String msg) {
System.out.println("msg=" + msg);
}
public void mouseClicked(MouseEvent e) {
int delay = 0;
for (ClickAction action : ClickAction.values()) {
// Schedule it.
executor.schedule(() -> {
action.execute();
}, delay, TimeUnit.MILLISECONDS);
// Add up all of the delays.
delay += action.delayAfter;
}
}
Upvotes: 1
Reputation: 479
CountDownLatch
may do what you want.
For example:
public void mouseClicked(MouseEvent e) {
try{
final CountDownLatch latch = new CountDownLatch(1);
demo.main("Welcome", latch);
latch.await();
}catch(Exception e){
e.printStackTrace();
}
}
Then in main you would call latch.countDown()
to continue beyond the await.
Upvotes: 0
Reputation: 272217
I would simply spawn off a new thread e.g. (the simplest example)
Thread t = new Thread(new Runnable() {
public void run() {
demo.main("Welcome");
Thread.sleep(900);
demo.main("Argument to main");
Thread.sleep(900);
demo.main("Argument to main");
}
});
t.start();
since you don't want block the Swing update thread (as you've noted). The above will invoke your demo
class in a background thread. I would perhaps investigate Java multithreading further - if you have more complex requirements you may wish to use higher level constructs than the simple Thread
object presented here.
Upvotes: 0