问题
i'm trying to set a delay when a button is pressed to set an imageicon to a certain image then set another delay so that another image would be set, all of this by single click. in other word :
click a button->set image->delay->set another image.
what i get in my code is the last state only "set another image".
also i don't want to use use timers, i want to use delays.
and here the part in my code i'm concerned about.
btnNewButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
lblNewLabel.setIcon(and);
sleeep(500);
lblNewLabel.setIcon(app);
}
});
and here is the delay function
void sleeep(int n)
{
try {
Thread.sleep(n);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
回答1:
don't add MouseListener to JButton, nor for
mouseClicked()
, add ActionListener instead, btw allMouse
andKey
events are implemented in JButton API and correctlydon't to use
Thread.sleep(n);
you have an issue with Concurency in Swing, use Swing Timer instead,
回答2:
You should try executing the code that sets the image in the event dispatch thread using InvokeLater.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
lblNewLabel.setIcon(and);
}
});
sleeep();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
lblNewLabel.setIcon(and);
}
});
来源:https://stackoverflow.com/questions/19953864/java-set-delay-to-change-imageicon