How to Draw an BufferedImage to a JPanel

前端 未结 2 1678
离开以前
离开以前 2020-12-01 22:57

I am trying to use some sort of draw method to draw a sprite image to my subclass of JPanel called AnimationPanel. I have created a Spritesheet class which can generate a Bu

2条回答
  •  渐次进展
    2020-12-01 23:40

    Here's some generic code for drawing an image to a JPanel. This method is called to paint your JPanel component.

    public void paintComponent (Graphics g)
    { 
         super.paintComponent(g);
         //I would have image be a class variable that gets updated in your run() method
         g.drawImage(image, 0, 0, this); 
    } 
    

    I may also modify run() to look something like this:

    public void run() {
      BufferedImage[] frames = sheet.getAllSprites();
      currentFrame = 0;
      while (true) {
        image = frames[currentFrame];
        this.repaint(); //explicitly added "this" for clarity, not necessary.
        currentFrame++;
        if (currentFrame >= frames.length) {
            currentFrame = 0;
        }
      }
    }
    

    In regards to only repainting part of the component, it gets a little more complicated

    public void run() {
      BufferedImage[] frames = sheet.getAllSprites();
      currentFrame = 0;
      while (true) {
        image = frames[currentFrame];
        Rectangle r = this.getDirtyRect();
        this.repaint(r); 
        currentFrame++;
        if (currentFrame >= frames.length) {
            currentFrame = 0;
        }
      }
    }
    
    public Rectangle getDirtyRect() {
      int minX=0; //calculate smallest x value affected
      int maxX=0; //calculate largest x value affected
      int minY=0; //calculate smallest y value affected
      int maxY=0; //calculate largest y value affected 
      return new Rectangle(minX,minY,maxX,maxY);
    }
    

提交回复
热议问题