我正在尝试编写一个 Mario 3 1 级克隆,之前,当我在 Mario 本身的构造函数中拉动 Sprite 时,我能够让它显示在 JFrames 中。然而,因为我意识到我需要将坐标和状态(小、大)等内容链接到移动图像本身,所以我决定将其撕碎并拥有 Mario 和 MarioComponent。我有一个 MarioComponent 类,但它没有显示。
public class MarioComponent extends JComponent{
private Mario m;
public MarioComponent(){
m = new Mario();
}
public void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D) g;
super.paintComponent(g2);
m.draw();
}
public void moveMario(){
m.move();
repaint();
}
public static void main(String[] args){
JFrame f = new JFrame();
f.setSize(868,915);
MarioComponent m = new MarioComponent();
m.setLocation(100,100);
f.add(m);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
}
我的马里奥类(class):
public class Mario{
//all numbers multiplied by 2 from OG game
protected MarioState state;
protected int x, y;
BufferedImage sprite;
public Mario(){
this.state = MarioState.SMALL;
this.x = 54;
this.y = 806;
}
public Mario(MarioState s, int x, int y){
this.state = s;
this.x = x;
this.y = y;
}
public void move(){
this.x+=2;
}
public void jump(){
this.y -= 46;
}
public String getCoordinates(){
return "Mario coords: " + this.x + ", " + this.y + ".";
}
public void draw(){
URL spriteAtLoc = getClass().getResource("sprites/Mario/SmallStandFaceRight.bmp");
try{
sprite = ImageIO.read(spriteAtLoc);
} catch(IOException e){
System.out.println("sprite not found");
e.printStackTrace();
}
}
}
当我尝试将 MarioComponent 放置在 JFrame 上时,它不在那里。我该如何解决这个问题?
最佳答案
您需要在您的paintComponent中使用Graphics对象g
(或g2
——它们是同一个对象)作为用于绘制的“笔” 。你不这样做,所以任何东西都无法或不应该渲染。 Graphics 有一个方法,g.drawImage(...)
,它接受图像作为其参数之一,这将是实现此功能的最佳方式。
建议:
- 更改绘制,使其接受 Graphics 参数:
public void draw(Graphics g){
- 在 PaintComponent 中,将 JVM 提供给方法的 Graphics 参数传递到绘图调用中:
m.draw(g);
- 不要在绘制方法中不断重新读取图像。这是浪费并且只会造成滞后。读取一次并将其存储到变量中。
- 当前绘制方法中的所有代码都不应该在那里。同样,图像应该被读入一次,可能是在构造函数中,而绘制应该实际绘制图像,而不是读取文件。
- 不要猜测这一点,而是阅读相应的教程
- Lesson: Performing Custom Painting :Swing 图形入门教程
- Painting in AWT and Swing :Swing 图形高级教程
关于java - 为什么我的 Mario Sprite(JComponent)没有出现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44990575/