1

I have 100 same JPanels, each contains JLabel with an icon and JLabel with text. When certain event occurs, I want to change icon and border of panel for 2.5 seconds, and then change them back. The problem is that 1st they are changed together, but when I try to change them back - first icon is changed, and then in 2 or 3 seconds border is changed. Here is the method of a JPanel to perform this:

public void showPacketCame() {  
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            img.setIcon(blue);
            setBorder(BorderFactory.createLineBorder(new Color(54, 208, 243)));

            javax.swing.Timer tim = new javax.swing.Timer(2500, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {                        
                    img.setIcon(onDark); 
                    setBorder(null);
                }
            });
            tim.setRepeats(false);
            tim.setDelay(2500);
            tim.start();
        }

    });
}
Zoyd
  • 3,449
  • 1
  • 18
  • 27
Natalia
  • 783
  • 7
  • 18
  • 1
    Both your methods were called right away; there must be some other reason why your border didn't respond to the method call `setBorder(null)`. – Marko Topolnik Jan 15 '13 at 11:01
  • 1
    You may want a _single_ `Timer` to change _all_ the panels. – trashgod Jan 15 '13 at 11:02
  • 1
    right as (@trashgod) mentioned, by default one Swing.Timer can do that – mKorbel Jan 15 '13 at 11:09
  • 1
    Please edit your question to include an [sscce](http://sscce.org/) that exhibits the problem you describe. – trashgod Jan 15 '13 at 11:28
  • @mKorbel Not sure I understand what you mean. Removed invokelater, but left first setIcon and setBorder outside Timer - that didn't help. Including everything in timer and calling Thread.sleep(2500) frozed GUI. – Natalia Jan 15 '13 at 11:39
  • Thread.sleep(2500) blocking EDT, then code execution from Swing Timer never will be executed to the screen, see this [my wish merry christmast as question](http://stackoverflow.com/questions/8614972/passing-current-date), there is only one Swing Timer and loop inside arrays of Objects, your JPanel (nested JLabel) is in Java the same Object – mKorbel Jan 15 '13 at 11:44
  • @mKorbel how to garanty events in this timer to be performed in certain order? Now even when I first call setBorder(null) and then img.setIcon(onDark), first imae is changed, and then border. – Natalia Jan 15 '13 at 12:18
  • there no guarantee that SwingTimer is accurate, next period starting when last is executed, but this could be / is important property – mKorbel Jan 15 '13 at 12:24

1 Answers1

-2

This is not the apt way of coding animation task. Please make use of SwingWorker for this purpose.

NiranjanBhat
  • 1,812
  • 13
  • 17