我对Java很新,并且还在学习它,但我想在JFrame中显示一个图像。我到处寻找答案,但是我还没有找到任何有用的东西,我有一个跟踪X和Y坐标的字符类,以及是否按下了一个键。以下是角色类的代码,如果有帮助的话。
import java.awt.Image;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
public class Char {
private String Char = "Char.png";
private int dx;
private int dy;
private int x;
private int y;
private Image image;
public Char() {
ImageIcon ii = new ImageIcon(this.getClass().getResource(Char));
image = ii.getImage();
x = 40;
y = 60;
}
public void move() {
x += dx;
y += dy;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public Image getImage() {
return image;
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT) {
dx = -1;
System.out.println("Left arrow key down.");
}
if (key == KeyEvent.VK_RIGHT) {
dx = 1;
System.out.println("Right arrow key down.");
}
if (key == KeyEvent.VK_UP) {
dy = -1;
System.out.println("Up arrow key down.");
}
if (key == KeyEvent.VK_DOWN) {
dy = 1;
System.out.println("Down arrow key down.");
}
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT) {
dx = 0;
System.out.println("Left arrow key up.");
}
if (key == KeyEvent.VK_RIGHT) {
dx = 0;
System.out.println("Right arrow key up.");
}
if (key == KeyEvent.VK_UP) {
dy = 0;
System.out.println("Up arrow key up.");
}
if (key == KeyEvent.VK_DOWN) {
dy = 0;
System.out.println("Down arrow key up.");
}
}
}
Board类应该在Char类中使用getImage方法并绘制图像,但我似乎在这行代码中得到错误:
ImageIcon ii = new ImageIcon(this.getClass().getResource(Char));
image = ii.getImage();
答案 0 :(得分:0)
确保图像位于类路径的根位置或Jar的根路径(如果它被打包为一个
)答案 1 :(得分:0)
//If the image is inside de classpath
ImageIcon ii = new ImageIcon(this.getClass().getResource("/path/to/image"));
//If the image outside de classpath
ImageIcon ii = new ImageIcon("/path/to/image"); //i.e. C:\\images\\x.png
答案 2 :(得分:0)
替换 this.getClass()with thenameofyourclass.class
如果你的类名是Craft(Zetcode),用Craft.class替换this.getClass() 并使用Char.png直接在.java文件旁边。它会起作用