【问题标题】:image as component issue图像作为组件问题
【发布时间】:2012-07-23 02:07:21
【问题描述】:

我正在尝试为我的 java 类做我的最终项目。我正在尝试拍摄 .png 图片并将其用作可以添加到 JFrame 的组件。但是,当我尝试执行此操作时,它会引发异常并执行 catch 语句中的操作。我不明白它为什么会这样做。我的 .png 文件与 .java 文件位于同一文件夹中。

package InventoryApp;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;

/**
 *
 * @author Curtis
 */
public class FinalProject extends DFrame
{
//main method
public static void main(String[] args) 
{
    start();
}

//building splash screen

public static void start()
{   DFrame splashFrame = new DFrame();
    try
    {
    BufferedImage myPicture = ImageIO.read(new File("logo.png"));
    JLabel picLabel = new JLabel(new ImageIcon( myPicture ));
    splashFrame.add(picLabel);
    }
    catch(IOException g)
    {
        JLabel error = new JLabel("Picture Could Not Be Found");
        splashFrame.add(error);
    }


    JButton create = new JButton("Click to Create Item List");
    JButton view = new JButton("Click to View Item List");
    splashFrame.add(create);
    splashFrame.add(view);


}

}

【问题讨论】:

  • 你能详细说明我是如何解决这个问题的吗?我以为它在尝试抓取文件时抛出了异常。
  • 在异常块中,需要打印异常。基本上你可以打电话给g.dumpStackTrace() 进行快速而肮脏的转储
  • @MadProgrammer ITYM printStackTrace() ;)
  • @AndrewThompson 是的,就是这样:P

标签: java image components


【解决方案1】:

当您创建一个未指定路径的File 对象时,它假定启动程序的目录,不是当前类文件所在的目录。您可能希望改用@ 987654322@:

BufferedImage myPicture = ImageIO.read(FinalProject.class.getResource("logo.png"));

【讨论】:

  • 你能帮我处理这段代码吗?我收到一个错误 BufferedImage myPicture = ImageIO.read(new File(FinalProject.class.getResource("logo.png")));
  • 抱歉,我的意思是你可以完全不用File,而使用带有URL 的ImageIO.read() 版本。
  • 感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 2021-12-20
  • 2023-04-01
  • 2021-05-18
  • 2020-06-29
  • 2011-01-02
  • 1970-01-01
  • 1970-01-01
  • 2012-11-15
相关资源
最近更新 更多