Hope my first question isn’t too obvious or badly researched. The below code is from the MouseListener’s mouseClicked event. I was hoping to change the border color to green to show the user what he/she has clicked on, start the sleep timer and then change it back to black. Unfortunately, the change only takes place after the Thread.sleep (and probably a whole host of methods). Currently the change back to black is commented and the color change does change to green (permanently). If it isn’t commented, there is no visible color change. What is going on here?
Thanks
JLabel myLabel = (JLabel) e.getSource();
myLabel.setBorder(BorderFactory.createLineBorder(Color.green));
try {
Thread.sleep(2000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//myLabel.setBorder(BorderFactory.createLineBorder(Color.black));
If you sleep in the event dispatch thread, you prevent it from doing its work, i.e. repaint the GUI and display the border you’ve just set. You’re just freezing the whole GUI for 2 seconds.
You need to use a swing Timer, and have this timer reset the border to its original color after 2 seconds. The sleep must be done in another thread, and then the border must be changed in the EDT. That’s what the Swing Timer does for you.