【发布时间】:2017-12-12 22:05:40
【问题描述】:
我正在尝试编写一个马里奥 3 1 级克隆,以前,当我在马里奥本身的构造函数中拉出精灵时,我能够让它显示在 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);
}
}
我的马里奥课:
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();
}
}
}
当我尝试在 JFrame 上放置 MarioComponent 时,它不存在。我该如何解决这个问题?
【问题讨论】: