Reputation: 85
I've made this code in java, i wanna make a delay after this part of code, but when i use delay or sleep codes the whole code sleeps for the delay time but i wanna see this back ground changes in gui and then make a delay!!! so what should i do?(I use swing gui)
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (matrisBazi[i][j] == 0) {
jb[i][j].setBackground(Color.white);
}
if (matrisBazi[i][j] == 1) {
jb[i][j].setBackground(Color.red);
}
if (matrisBazi[i][j] == 2) {
jb[i][j].setBackground(Color.blue);
}
}
}
jb[i][j].addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
click(s);
}
});
my actionPerformed void is called before and its inside of click(); functions and is doing the process so how to add swing timer code to this void?! i think the timer doesn't work until the click(); finished.
Upvotes: 3
Views: 581
Reputation: 7764
You need to use a Swing timer (javax.swing.Timer) because you have a GUI.
Read about it in this tutorial:
How to use Swing timers
Upvotes: 4
Reputation: 285403
If this is a Swing GUI (you don't tell us), you'll not want to use Thread.sleep(...)
as it will sleep the Swing event thread and put the entire application to sleep. Instead you'll want to use a Swing Timer.
Note that if you'll be incrementing a variable slowly, you'll not use a for loop, but instead will increment the variable directly inside of the Timer's actionPerformed method.
For example this:
for (int i = 0; i < MAX; i++) {
// do some animation using i
Thread.sleep(sleepTime);
}
would be changed to:
new Timer(sleepTime, new ActionListener(){
private int i = 0;
public void actionPerformed(ActionEvent evt) {
if (i >= MAX) {
// stop the animation
}
// do some animation with i
i++;
}
}).start();
Upvotes: 4