0

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

3 回答 3

0

确保图像位于类路径的根位置或 Jar 的根路径(如果它被打包为一个)

于 2012-08-07T19:48:45.907 回答
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
于 2012-08-07T19:51:44.080 回答
0

用你的类名替换 this.getClass()

如果您的类名是 Craft (Zetcode),则将 this.getClass() 替换为 Craft.class 和直接在 .java 文件旁边的 Char.png。它会工作

于 2013-01-01T08:23:41.577 回答