I am a beginner and I am trying to make a card flip game in netbeans

Viewed 180

On clicking an image I want another image to be displayed pause for one second and the original image to be restored and displayed againdisplayed again When I try to do it it action handler such as code given below it sets the image after sleep .I want the image to be displayed pause and the original to be displayed again how can I achieve that

private void jButton16ActionPerformed(java.awt.event.ActionEvent evt) {                                           
    jButton16.setIcon(new javax.swing.ImageIcon("C:\\Users\\x\\Documents\\O.png"));  
    try {           //sleep 1 seconds 
        Thread.sleep(1000);
    } 
    catch (InterruptedException e)
    {                   
    }

    jButton16.setIcon(new javax.swing.ImageIcon("C:\\Users\\x\\Documents\\118px-AMIGO.jpg"));     }                                         
2 Answers

You should never invoke Thread.sleep() inside Event Dispatch Thread because Thread.sleep() will block Event Dispatch Thread and your UI will be Freeze , instead you could use a Timer to achieve your goal

Refer below code,

    jButton16.setIcon(new javax.swing.ImageIcon("C:\\Users\\x\\Documents\\O.png"));
    Timer timer = new Timer(1000, new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            jButton16.setIcon(new javax.swing.ImageIcon("C:\\Users\\x\\Documents\\118px-AMIGO.jpg"));
        }
    });
    timer.setRepeats(false);
    timer.start(); 
  • Swing is single threaded, you should never perform long running or blocking operations within the context of the Event Dispatching Thread
  • Swing is NOT thread safe, this means you should never update the UI (and anything the UI needs) outside of the context of the EDT

The simplest solution to your problem is to use a Swing Timer

private void jButton16ActionPerformed(java.awt.event.ActionEvent evt) {                                           
    jButton16.setIcon(new javax.swing.ImageIcon("C:\\Users\\x\\Documents\\O.png"));  
    Timer timer = new Timer(1000, new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            jButton16.setIcon(new javax.swing.ImageIcon("C:\\Users\\x\\Documents\\118px-AMIGO.jpg"));     
        }
    });
    timer.setRepeats(false);
    timer.start();
}         

See Concurrency in Swing and How to use Swing Timers for more details

Related