Show an animated BG in Swing

后端 未结 3 727
忘了有多久
忘了有多久 2020-11-22 15:51

An animated (cycling) GIF can be displayed in a JLabel or in HTML (in formatted text components like JEditorPane) and be seen to cycle.

But

3条回答
  •  梦谈多话
    2020-11-22 16:11

    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.

提交回复
热议问题