我正在尝试将图像加载到此程序中,它将无法正常工作,我已经玩过以确保我的目录正确且一切都正常,但现在我有点迷失了。 PersonFront类调用的绘制函数工作正常,但不是应该在其中的Image。我可以改变尺寸和所有这些,但它仍然没有显示任何图像。
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
public class GameViewer extends Applet implements KeyListener
{
final static int NUM_WIDTH=14;
final static int NUM_HEIGHT=7;
private int startX = 100;
private int startY = 40;
public void init()
{
setBackground(Color.GRAY);
addKeyListener(this);
setFocusable(true);
requestFocusInWindow();
}
public void start()
{}
public void paint(Graphics g)
{
Graphics2D g2 =(Graphics2D) g;
Image wood = getImage(getCodeBase(), "Resources/Images/Environment/woodfloor.png");
Image wall = getImage(getCodeBase(), "wall.jpg");
Image counter = getImage(getCodeBase(), "resources/images/environment/counter.jpg");
Image cab_right = getImage(getCodeBase(), "resources/images/environment/cabinet_right.jpg");
Image cab_left = getImage(getCodeBase(), "resources/images/environment/cabinet_left.jpg");
Image shirt = getImage(getCodeBase(), "resources/Images/Character_Wear/Shirts/shirt_red.png");
Image pants = getImage(getCodeBase(),"resources/Images/Character_Wear/Pants/pants_limegreen.png");
g2.drawImage(wood,0,0,null);
//for(int q=0; q<NUM_WIDTH; q++)
// for(int z=0; z<NUM_HEIGHT; z++)
// {
// g2.drawImage(wood, q*64, z*64, null);
// g2.drawImage(wall, 0, 128+(16*z), null);
// }
PersonFront stat = new PersonFront(startX,startY,shirt,pants);
stat.draw(g2);
}
public void keyPressed(KeyEvent key)
{
if (key.getKeyCode() == key.VK_D)
{
startX += 32;
repaint();
}
if(key.getKeyCode() == key.VK_A)
{
startX -= 32;
repaint();
}
}
public void keyReleased(KeyEvent e)
{
}
public void keyTyped(KeyEvent e)
{
}
}
答案 0 :(得分:0)
您需要使用BufferedImages。
BufferedImage wood = this.getClass().getResource("Resources/Images/Environment/woodfloor.png");
请记住,图像文件必须位于JAR或与代码相同的目录中,相对于类文件(this)。
来源: 先验知识, loading BufferedImage with ClassLoader.getResource()