7

I Would like to realize the following loading animation with java swing :

enter image description here

The circle has to spin clockwise.

What would be the best way to make it ?

Thank you very much.

Vincent Roye
  • 2,751
  • 7
  • 33
  • 53

4 Answers4

9

Just use an ImageIcon and an animated gif. see setImageObserver in ImageIcon.

Loading icons can be made using a variety of online generators such as AjaxLoad.

Stephan
  • 41,764
  • 65
  • 238
  • 329
Jakob Weisblat
  • 7,450
  • 9
  • 37
  • 65
8

Hopefully it's not too late for this.

I managed to get the animated gif inside my JPanel this way:

private JPanel loadingPanel() {
    JPanel panel = new JPanel();
    BoxLayout layoutMgr = new BoxLayout(panel, BoxLayout.PAGE_AXIS);
    panel.setLayout(layoutMgr);

    ClassLoader cldr = this.getClass().getClassLoader();
    java.net.URL imageURL   = cldr.getResource("img/spinner.gif");
    ImageIcon imageIcon = new ImageIcon(imageURL);
    JLabel iconLabel = new JLabel();
    iconLabel.setIcon(imageIcon);
    imageIcon.setImageObserver(iconLabel);

    JLabel label = new JLabel("Loading...");
    panel.add(iconLabel);
    panel.add(label);
    return panel;
}

Some points of this approach:
1. The image file is within the jar;
2. ImageIO.read() returns a BufferedImage, which doesn't update the ImageObserver;
3. Another alternative to find images that are bundled in the jar file is to ask the Java class loader, the code that loaded your program, to get the files. It knows where things are.

So by doing this I was able to get my animated gif inside my JPanel and it worked like a charm.

Paulo Pedroso
  • 3,555
  • 2
  • 29
  • 34
  • 1
    animated gif is no option, because it lacks good and smooth transparent effects. A spinner mostly needs to be transparent and with 100% transparent background, which gifs do not support, without making the animation ugly and pixelated. It just works for rectangle borders and without fading between objects. So... how to do this correctly? APNG could do it, but of course Java does not support it withouth libs. – M. H. May 11 '17 at 07:38
4

You can use the Animated Icon class to create your own animation using your existing icon.

camickr
  • 321,443
  • 19
  • 166
  • 288
3

This could be drawn with a custom component or a custom icon, using regular Java2D calls. To me it looks like an Arc2D with a fairly thick BasicStroke drawn with a GradientPaint.

Alternately, export frames from Inkscape (or other graphics program) and load them as images.

Russell Zahniser
  • 16,188
  • 39
  • 30