在 Netbeans 中读取图像 [英] Reading an image in Netbeans
问题描述
我的项目中有一个图像文件.层次结构如下所示:
I have an image file in my project. The hierarchy looks like this:
我正在尝试使用以下代码将 Manling.png 读入 Manling.java:
I'm trying to read Manling.png into Manling.java using this code:
public BufferedImage sprite;
public Manling()
{
try
{
File file = new File("resources/Manling.png");
sprite = ImageIO.read(file);
} catch (IOException e) {}
System.out.println(sprite.toString()); //This line is to test if it works
}
我总是在 println
语句上得到一个 NullPointerException
,所以我认为路径是错误的.我尝试将图像移动到项目中的不同位置,并尝试更改文件路径(例如mine/resources/Manling.png"和/resources/Manling.png").有什么想法吗?
I always get a NullPointerException
on the println
statement, so I assume the path is wrong. I've tried moving the image to different places in the project and I've tried changing the file path (e.g. 'mine/resources/Manling.png' and '/resources/Manling.png'). Any ideas?
如果你想要一个完整的可编译示例,试试这个:
If you want a full compilable example, try this one:
package minesscce;
import javax.swing.*;
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import java.net.URL;
public class Mine extends JFrame
{
private BufferedImage sprite;
public static void main(String args[])
{
Mine mine = new Mine();
}
public Mine()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setSize(800, 600);
setExtendedState(Frame.MAXIMIZED_BOTH);
setBackground(Color.WHITE);
try
{
File file = new File("resources/Manling.png");
sprite = ImageIO.read(file);
} catch (IOException e) {}
System.out.println(sprite.toString());
}
public void paint(Graphics g)
{
g.translate(getInsets().left, getInsets().top);
Graphics2D g2d = (Graphics2D)g;
g2d.drawImage(sprite, 0, 0, this);
Toolkit.getDefaultToolkit().sync();
g2d.dispose();
}
}
只需像这样设置项目,使用您想要的任何图像:
Just set up the project like this, using any image you want:
推荐答案
尝试
ImageIO.read(Mine.class.getResource("../minesscce.resources/Manling.png"));
<小时>
这是一个例子:
Here's an example:
- 层次结构
- 结果
这是代码...
public final class ImageResourceDemo {
private static BufferedImage bi;
public static void main(String[] args){
try {
loadImage();
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
createAndShowGUI();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
private static void loadImage() throws IOException{
bi = ImageIO.read(
ImageResourceDemo.class.getResource("../resource/avatar6.jpeg"));
}
private static void createAndShowGUI(){
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setBackground(Color.WHITE);
frame.add(new JLabel(new ImageIcon(bi)));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
这篇关于在 Netbeans 中读取图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!