Java 为什么我的马里奥雪碧(JComponent)没有出现?

Java 为什么我的马里奥雪碧(JComponent)没有出现?,java,swing,Java,Swing,我正在尝试编写一个马里奥3 1级克隆,之前,当我在马里奥自身的构造器中拉动精灵时,我能够让它出现在JFrames中。然而,因为我意识到我需要将坐标和状态小,大与运动图像本身联系起来,所以我决定把它撕碎,并有一个Mario和MarioComponent。我有一个MarioComponent类,但它没有出现 public class MarioComponent extends JComponent{ private Mario m; public MarioComponent(){

我正在尝试编写一个马里奥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时,它不在那里。如何解决此问题?

您需要使用图形对象g或g2-它们在您的画笔组件中与画笔是同一个对象。你不这样做,所以没有任何东西可以或应该呈现。图形有一种方法,g.drawImage。。。它接受图像作为其参数之一,这将是实现此功能的最佳方式

建议:

更改draw以使其接受图形参数:public void drawGraphics g{ 在paintComponent中,将JVM提供给方法的图形参数传递到draw调用中:m.drawg; 不要在draw方法中重复读取图像。这是浪费,只会导致延迟。请读入一次并将其存储到变量中。 当前draw方法中的所有代码都不应该存在。同样,图像应该读取一次,很可能是在构造函数中,draw应该实际绘制图像,而不是读取文件。 不要猜测,而是阅读适当的教程 :Swing图形的入门教程 :Swing图形高级教程
Mario的构造函数,还是MarioComponent?@Derry:你告诉我;试试你认为哪一个最好,看看它是否有效。@Derry:现在开始工作?好吧,我让它画图,我在Mario.draw中调用了drawImage,在它的签名中添加了一个图形对象,并将paint的调用添加到了paintComponent中,并将Mario的draw方法的内容移动到int中o构造函数,现在Sprite是一个实例变量。这就是你的意思吗?@dery:可能,可能。draw看起来像m.drawg;?