【问题标题】:Why isn't my picture showing anymore为什么我的图片不再显示
【发布时间】:2014-07-27 04:54:36
【问题描述】:

今天早上我正在测试我的程序并运行它,它运行良好。一个小时后,我的按钮不再出现我的图像了,我不知道为什么。

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");
        }
    }
});

【问题讨论】:

  • 是时候做一些调试了。
  • 您的图像存储在哪里?我也劝你不要使用 null 布局
  • 我的图像与我的 java 文件一起存储在一个文件夹中
  • 尝试将图片放在存放.class文件的文件夹中

标签: java image swing embedded-resource imageicon


【解决方案1】:

我的图像与我的 java 文件一起存储在一个文件夹中

这表明图像实际上是嵌入式资源,不能像文件系统上的普通文件一样被引用。

ImageIcon(String) 假定 String 引用指向文件系统上的文件。构建后,这将不再是true,而是您需要根据需要使用Class#getResourceClass#getResourcesAsStream,例如...

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

更好的解决方案是使用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();
} 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多