简体   繁体   English

为什么我的照片不再显示

[英]Why isn't my picture showing anymore

This morning I was testing my out my program and just running it through and it was working well. 今天早上,我正在测试我的程序,然后运行它,它运行良好。 After an hour my images just stopped appearing on my buttons I'm not sure why. 一个小时后,我的图像刚刚停止出现在我的按钮上,我不确定为什么。

JButton chuck = new JButton(new ImageIcon("chucknorris.jpg"));//this part of program runs this if user picks lizard
chuck.setSize(210,175); //sets size of button
chuck.setLocation(25,75); //sets location of button
chuck.addActionListener(new ActionListener() {
    public void actionPerformed (ActionEvent e) {    
        int answer = JOptionPane.showConfirmDialog(null, "\t\t                  STATS\nAttack:      10\nDefence:   15\nspecial:   bomb");

        if (answer == JOptionPane.NO_OPTION) {
            System.out.println("No button clicked");
        } else if (answer == JOptionPane.YES_OPTION) {
            x = 1;
            b = 0;
        } else if (answer == JOptionPane.CLOSED_OPTION) {
            System.out.println("JOptionPane closed");
        }
    }
});

my images are stored in a folder with my java file 我的图像与我的Java文件存储在一个文件夹中

This suggests that the images are, in fact, embedded resources and can't be referenced like normal files on the file system. 这表明图像实际上是嵌入式资源,不能像文件系统上的普通文件一样被引用。

ImageIcon(String) assumes that the String reference is referring to a file on the file system. ImageIcon(String)假定String引用引用文件系统上的文件。 Once built, this will no longer be true , instead, you need to use Class#getResource or Class#getResourcesAsStream depending on your needs, for example... 构建完成后,它将不再是true ,而是需要根据需要使用Class#getResourceClass#getResourcesAsStream ,例如...

JButton chuck = new JButton(new ImageIcon(getClass().getResource("chucknorris.jpg")));

A better solution would be to use ImageIO.read as this will actually throw an IOException if the image can't be loaded for some reason, rather than failing silently 更好的解决方案是使用ImageIO.read因为如果由于某种原因无法加载图像,这实际上会抛出IOException ,而不是静默失败

try {
    BufferedImage img = ImageIO.read(getClass().getResource("chucknorris.jpg"));
    JButton chuck = new JButton(new ImageIcon(img));
} catch (IOException exp) {
    JOptionPane.showMessageDialog(null, "Check has left the building");
    exp.printStackTrace();
} 

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

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