swing不会在jbuttons上显示png图标

时间:2018-05-10 19:24:21

标签: java image swing runtime-error png



我在java中编写了一个简单的JFrame并添加了一个按钮。 然后我在按钮上添加了一个.png图标,但它一直给我一个例外。 (我对.jpg图标没有任何问题,效果很好)

以下是我的代码和例外情况。

public class Test
{
    static JFrame mainFrame;
    public static void main(String[] args)
    {
        mainFrame = new JFrame("a");
        mainFrame.setSize(300, 300);
        mainFrame.setLocation(50, 50);
        JButton btn = new JButton();
        ImageIcon icon = new ImageIcon("C:\\a.png");
        btn.setIcon(icon);
        btn.setSize(100, 100);
        btn.setLocation(50, 50);
        mainFrame.add(btn);
        mainFrame.setVisible(true);
    }
}

例外:

sun.awt.image.PNGImageDecoder$PNGException: Broken file
    at sun.awt.image.PNGImageDecoder.pngassert(PNGImageDecoder.java:94)
    at sun.awt.image.PNGImageDecoder.handleChunk(PNGImageDecoder.java:107)
    at sun.awt.image.PNGImageDecoder.getData(PNGImageDecoder.java:726)
    at sun.awt.image.PNGImageDecoder.produceImage(PNGImageDecoder.java:252)
    at sun.awt.image.InputStreamImageSource.doFetch(InputStreamImageSource.java:269)
    at sun.awt.image.ImageFetcher.fetchloop(ImageFetcher.java:205)
    at sun.awt.image.ImageFetcher.run(ImageFetcher.java:169)
sun.awt.image.PNGImageDecoder$PNGException: Broken file
    at sun.awt.image.PNGImageDecoder.pngassert(PNGImageDecoder.java:94)
    at sun.awt.image.PNGImageDecoder.handleChunk(PNGImageDecoder.java:107)
    at sun.awt.image.PNGImageDecoder.getData(PNGImageDecoder.java:726)
    at sun.awt.image.PNGImageDecoder.produceImage(PNGImageDecoder.java:252)
    at sun.awt.image.InputStreamImageSource.doFetch(InputStreamImageSource.java:269)
    at sun.awt.image.ImageFetcher.fetchloop(ImageFetcher.java:205)
    at sun.awt.image.ImageFetcher.run(ImageFetcher.java:169)

1 个答案:

答案 0 :(得分:-1)

代码很好,您的图像文件存在问题