简体   繁体   English

在JFrame上刷新图像

[英]Refresh image on the JFrame

I want to show JLabel with text and image GIF. 我想用文本和图像GIF显示JLabel。 When i call showLabel() method from Test class i see only text. 当我从Test类调用showLabel()方法时,我只能看到文本。 I don't know how to refresh this image to show it. 我不知道如何刷新此图像以显示它。 I read is problem with AWT in this case... 在这种情况下,我读到AWT有问题...

Question: How to show this GIF image in my JLabel? 问:如何在我的JLabel中显示此GIF图像?

LabelTest.class LabelTest.class

public class LabelTest{

    private JWindow frame;
    private JLabel jLabel;
    ImageIcon icon = new ImageIcon("PHOTO.gif");    

    public LabelTest() {
    }

    public void showLabel(String label) {
        frame = new JWindow();
        frame.setAlwaysOnTop(true);
        frame.setBackground(new Color(255, 255, 255));
        frame.setContentPane(new TranslucentPane());
        frame.add(new JLabel(label, icon, JLabel.CENTER));
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        frame.paintAll(frame.getGraphics());
    }

    public void hideLabel() {
        frame.dispose();
    }
}

Test.class 测试类

public class Test {
    public static void main(String[] args){     
        try {
            LabelTest p = new LabelTest();
            p.showLabel("I'M LABEL...");
            Thread.sleep(5000);     
            p.hideLabel();
        } catch(InterruptedException ex) {
            Thread.currentThread().interrupt();
        }
    }
}

TranslucentPane.class TranslucentPane.class

public class TranslucentPane extends JPanel {
    public TranslucentPane() {
        setOpaque(true);
    }
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g); 
    }
}

I agree with LuxxMiner. 我同意LuxxMiner。
Most probably, the image can't be found. 最有可能找不到该图像。
To check the path you can use the following check: 要检查路径,可以使用以下检查:

public ImageIcon loadImageIconFromPath(String path) {
    URL imgURL = getClass().getResource(path);
    if (imgURL != null) {
        return new ImageIcon(imgURL);
    } else {
        System.err.println("Couldn't find file: " + path);
        return null;
    }
}

So instead of: 所以代替:

frame.add(new JLabel(label, icon, JLabel.CENTER));

Try the following: 请尝试以下操作:

ImageIcon icon = loadImageIconFromPath("PHOTO.gif");    
if (icon != null)
    frame.add(new JLabel(label, icon, JLabel.CENTER));
else 
    frame.add(new JLabel("Missing image", JLabel.CENTER));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM