0

I am working on a "concentration" type matching game. The pictures are displayed on JButton objects. When you click a button, I need to "show" the image for that button (images are in a parallel array) by using setIcon, which works. But if there is no match I want to reset the image to the "back" image. But I need a pause so that the player can see the image for a few seconds before turning over. There must be something I am not understanding about the mechanics of when/how the icon is displayed. Here is a simplified version of what I am trying to do is in this pastebin

import java.awt.event.ActionEvent; import java.awt.event.ActionListener;

import javax.swing.*;

public class DelayGUI extends JFrame {

private JPanel panel;
private JButton btnClick;
private ImageIcon img1, img2;

public DelayGUI()
{
super("Delay Test");
img1 = new ImageIcon("back.png");
img2 = new ImageIcon("leia.png");
panel = new JPanel();
btnClick = new JButton(img1);
panel.add(btnClick);
btnClick.addActionListener(new ButtonHandler());    
add(panel);     
}

private class ButtonHandler implements ActionListener
{
@Override
public void actionPerformed(ActionEvent e) 
{
//"show" the image
btnClick.setIcon(img2);
//delay 
try {
Thread.sleep(5000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
// now change pic back
//btnClick.setIcon(img1);       
}//end actionPerformed

}//end ButtonHandler class

public static void main(String[] args) 
{
// create object
DelayGUI frame = new DelayGUI();
frame.setSize(300, 300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

}

If there is a better way for me to show the code please let me know. This code expects two picture files "back.png" and "leia.png" in the folder.

I have the delay AFTER changing the icon, but when I run it there is a delay first before it changes. What am I missing about how this actually works?

  • 1
    Q: What does `Thread.sleep` do? A: it puts the current thread to sleep. Q: what thread is the current thread, and what does it do? A: The current thread is the Swing event thread (or EDT -- event dispatch thread), and it is responsible for interacting with the user and drawing the application. Q: what happens when this thread goes to sleep? A: Your whole app goes to sleep -- gets frozen. – Hovercraft Full Of Eels Mar 25 '20 at 23:07
  • Solution: use a Swing Timer instead. [For example](https://stackoverflow.com/a/35972179/522444) – Hovercraft Full Of Eels Mar 25 '20 at 23:07
  • Thanks for the clarification. I was going to try a timer but was trying to understand why this didn't work. – Pamela Price Mar 25 '20 at 23:34
  • Also, for future reference, please no links to pastebin or other code repository. All pertinent code must be in the question itself. – Hovercraft Full Of Eels Mar 26 '20 at 00:01

0 Answers0