java set delay to change imageicon

一曲冷凌霜 提交于 2021-02-05 12:18:57

问题


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:


  1. don't add MouseListener to JButton, nor for mouseClicked(), add ActionListener instead, btw all Mouse and Key events are implemented in JButton API and correctly

  2. don'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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!