sách gpt4 ai đã đi

Gặp khó khăn khi lấy hình ảnh (người mới)

In lại 作者:行者123 更新时间:2023-12-01 15:15:31 46 4
mua khóa gpt4 Nike

我在获取图像以显示在我的 J Frame 中时遇到问题。我确信我将文件放在正确的位置并且输入了正确的名称。这是代码

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.io.File;
import java.net.URL;

import javax.swing.JFrame;


public class DrawImage extends JFrame {
private Image image;
public static void main(String[] args){
new DrawImage();
}
public DrawImage(){
super("DrawImage");
setSize(600,600);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
File appBase = new File("."); //current directory
String path = appBase.getAbsolutePath();
System.out.println(path);
Toolkit tk = Toolkit.getDefaultToolkit();
image= tk.getImage(getURL("Castle.jpg"));
}
private URL getURL(String filename){
URL url=null;
try{
url=this.getClass().getResource(filename);
//url=DrawImage.class.getResource(filename);
//url=C:\hw/myProg/Graphics2d/Castle.jpg;
}
catch(Exception e){
System.out.print("spleen:");
}
return url;
}
public void paint(Graphics g){
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.BLACK);
g2d.fillRect(0, 0, getSize().width, getSize().height);
g2d.drawImage(image, 0, 40, this);
}

}

我得到的是带有黑色但没有图像的 JFrame,并将其写入到 cousle。

C:\hw\myProg\Graphics2d\.
Uncaught error fetching image:
java.lang.NullPointerException
at sun.awt.image.URLImageSource.getConnection(Unknown Source)
at sun.awt.image.URLImageSource.getDecoder(Unknown Source)
at sun.awt.image.InputStreamImageSource.doFetch(Unknown Source)
at sun.awt.image.ImageFetcher.fetchloop(Unknown Source)
at sun.awt.image.ImageFetcher.run(Unknown Source)

当然,我的图像文件位于 C:\hw\myProg\Graphics2d\CaSTLe.jpg 那么我做错了什么?编辑:好的,我发现你可以从这段方便的代码中测试你的 ide 符合哪个文件夹。在 Eclipse 中它位于 bin 文件夹中。

URL test = DrawImage.class.getResource("/");
System.out.println(test);

1 Câu trả lời

根据错误,CaSTLe.jpg 不在类加载器类路径上下文中。如果图像未在应用程序中 Jar'ed,您可以使用 Tài liệu 对象来生成 URL,但我认为这不是您想要做的。

你可以:

  • 确保您正在从程序文件“C:\hw\myProg\Graphics2d”执行。
  • 将应用程序(及其资源)打包到 jar 中

关于java - 获取图像时遇到问题(新手),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11661271/

46 4 0
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com