【问题标题】:Why Doesn't My Mario Sprite (a JComponent) Show Up? [duplicate]为什么我的 Mario Sprite(一个 JComponent)不显示? [复制]
【发布时间】: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 时,它不存在。我该如何解决这个问题?

【问题讨论】:

    标签: java swing


    【解决方案1】:

    您需要在您的paintComponent 中使用Graphics 对象g(或g2——它们是同一个对象)作为绘制的“笔”。你不这样做,所以没有任何东西可以或应该呈现。 Graphics 有一个方法,g.drawImage(...),它接受图像作为其参数之一,这将是实现此功能的最佳方式。

    建议:

    • 更改 draw 使其接受 Graphics 参数:public void draw(Graphics g){
    • 在paintComponent 中,将JVM 提供给该方法的Graphics 参数传递给您的draw call:m.draw(g);
    • 不要在 draw 方法中不断地重新读取图像。这是浪费的,只会导致滞后。 读取一次并将其存储到变量中。
    • 当前绘制方法中的所有代码都不应该存在。同样,应该在构造函数中读取一次图像,而 draw 应该实际绘制图像,而不是读取文件。
    • 不要猜测,而是阅读相应的教程

    【讨论】:

    • Mario 的构造函数,还是 MarioComponent?
    • @Derry: 你告诉我 ;) 试试你认为最好的,看看它是否有效。
    • @Derry:现在工作吗?
    • 好的,所以我开始绘制了,我在 Mario.draw() 中调用了 drawImage,并在其签名中添加了一个 Graphics 对象,并且确实将 paint 的调用添加到了 paintComponent,并移动了内容将马里奥的draw()方法放到构造函数中,现在Sprite是一个实例变量。你是这个意思吗?
    • @Derry:可能,可能。 draw 看起来像 m.draw(g); 吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-24
    • 2022-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多