我对 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();