Java Graphics:setClip vs clipRect vs repaint(int,int,int,int)

时间:2014-12-16 16:29:54

标签: java swing animation graphics2d

与我上次的帖子道歉相似,但不那么长的啰嗦。基本上我想知道什么是优化重绘到JFrame / JPanel的最佳选项,当每次重绘调用只会重绘屏幕的一小部分时。

除了重载重绘之外,我不是100%关于如何实现setClip或clipRect。我的理解是在重写油漆或更新时使用它们? 请参阅下面的代码:

public class AquaSim extends JPanel {
//variables
//other methods...
    public void paint (Graphics g) {
       super.paintComponent(g); //needed?
       Graphics2D g2d = (Graphics2D) g;

        //Draws the land area for penguins.
        g2d.setColor(new Color(121,133,60));
        g2d.fill(land);
        g2d.setColor(Color.BLUE);
        g2d.fill(sea);

        drawCreatures(g2d);
}
    public void drawCreatures(Graphics2D g2d) {
        for (Creature c : crlist) //a list of all alive creatures {
            //each creature object stores its image and coords.
            g2d.drawImage(c.createImage(txs,tys), c.getPos(1).width, c.getPos(1).height, this);
        }
    }
}

理想情况下,我宁愿不必每个重绘请求循环每个生物对象,这是此帖的原因之一。我不知道是否有一种方法可以将当前生物被绘制为绘制或覆盖Creature类中的绘制,以使其自身绘制到主类中的图形对象。 多一点代码......

private class Creature implements ActionListener {
//variables & other methods
        @Override
        public void actionPerformed(ActionEvent e) {
            if (getState()!=State.DEAD) {
                move();
                repaint(); //<---Would rather set clipping area in paint/update. x,y,w,h needs to include ICON & INFO BOX.
                //repaint(gx,gy,getPos(1).width,getPos(1).height);
            }
            else anim.stop();
        }
//...


  public void move() {
    //Determines how it will move and sets where to here by updating its position that is used in drawCreatures.
    }
}

那么任何建议哪种方法最有效?令人印象深刻的重绘将被许多物体/生物大量调用,即每秒多次,因此我不希望它重新绘制每个重绘请求在屏幕上的每一个。

2 个答案:

答案 0 :(得分:3)

  

只会重新绘制屏幕的一小部分。

使用repaint(....)

RepaintManager会担心需要绘制的内容,并会为您设置Graphics对象的剪辑。

答案 1 :(得分:0)

只是出于兴趣,可以将Graphics对象附加到AquaSim中的JPanel全局,然后从每个Creature对象中使用此图形对象绘制到JPanel?

虽然我想我需要弄清楚如何在Creature类中实现/覆盖paint方法,就像Gilbert试图告诉我一样。