0

I am trying to implement a Fish Eye Image Menu in a JavaBean. As a start, I created a JLabel and put this code on the mouseEntered event. But when I run this, the output is shaky and doesn't re-size the JLabel.

This is my code.

new Thread() {
  public void run() {
    for (int i = 0; i < 30; i++) {
      int x = imgLabel.getWidth()+1;
      int y = imgLabel.getHeight()+1;
      imgLabel.setSize(x , y );

      // sets the icon to the label
      imgLabel.setIcon(new ImageIcon(new ImageIcon(getClass().getResource("/pics/icon.png")).getImage().getScaledInstance(x , y, Image.SCALE_DEFAULT)));
      repaint();
      try {
        Thread.sleep(10);
      } catch (InterruptedException ex) {
        ex.printStackTrace();
      }
    }
  }
}.start();

If I comment that line where I set the image to the JLabel, the label gets re-sized perfectly.
Where has this gone wrong?

trashgod
  • 203,806
  • 29
  • 246
  • 1,045
Praneeth Peiris
  • 2,008
  • 20
  • 40
  • 1
    For better help sooner, post an [SSCCE](http://sscce.org/). – Andrew Thompson Apr 12 '13 at 09:48
  • 3
    BTW - I would be more surprised if that mess of code lines worked, than failed. 1) [Don't call setSize(..)](http://stackoverflow.com/questions/7229226/should-i-avoid-the-use-of-setpreferredmaximumminimumsize-methods-in-java-swi) 2) Do GUI updates on the EDT. 3) Don't sleep on the EDT. See [Concurrency in Swing](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/) for more details. – Andrew Thompson Apr 12 '13 at 09:51
  • I know it's a messy code as I couldn't think of another way. Anyhow, thanks a lot for the comment and the links you provided. It was a great help. – Praneeth Peiris Apr 19 '13 at 18:15

1 Answers1

1

The problem is that getScaledInstance() together with resource loading is slow. Do these calculations once and cache them (in an array of 30 items). Not every time in the for loop.

Another thing: make sure you use a Swingworker for your animation, that helps in the timing and avoids setting icons outside the Event Dispatch Thread (EDT).

bluevoid
  • 1,274
  • 13
  • 29