java – 了解BufferStrategy

栏目: Java · 发布时间: 6年前

内容简介:翻译自:https://stackoverflow.com/questions/13590002/understand-bufferstrategy

我是 java 的新手.我想做一个游戏.经过大量的研究,我无法理解bufferstrategy的工作原理.

我知道基础知识..它创建了一个屏幕外图像,您可以稍后将其放入您的 Windows

对象..我得到了这个

public class Marco extends JFrame {
    private static final long serialVersionUID = 1L;
    BufferStrategy bs; //create an strategy for multi-buffering.

    public Marco() {
       basicFunctions(); //just the clasics setSize,setVisible,etc
       createBufferStrategy(2);//jframe extends windows so i can call this method 
       bs = this.getBufferStrategy();//returns the buffer strategy used by this component
    }

   @Override
   public void paint(Graphics g){
      g.drawString("My game",20,40);//some string that I don't know why it does not show
      //guess is 'couse g2 overwrittes all the frame..
      Graphics2D g2=null;//create a child object of Graphics
      try{
         g2 = (Graphics2D) bs.getDrawGraphics();//this new object g2,will get the
         //buffer of this jframe?
         drawWhatEver(g2);//whatever I draw in this method will show in jframe,
         //but why??
      }finally{
         g2.dispose();//clean memory,but how? it cleans the buffer after
         //being copied to the jframe?? when did I copy to the jframe??
      }
      bs.show();//I never put anything on bs, so, why do I need to show its content??
      //I think it's a reference to g2, but when did I do this reference??
   }

   private void drawWhatEver(Graphics2D g2){
       g2.fillRect(20, 50, 20, 20);//now.. this I can show..
   }
  }

我不知道..我已经研究了很长时间了……而且根本没有运气……我不知道……也许它就在那里,而且它非常简单明了,我我看起来太傻了..

感谢所有的帮助..

以下是它的工作原理:

>当您调用createBufferStrategy(2);时,JFrame构造一个BufferStrategy. BufferStrategy知道它属于JFrame的特定实例.您正在检索它并将其存储在bs字段中.

>当你需要绘制你的东西时,你正在从bs中检索Graphics2D.此Graphics2D对象绑定到bs拥有的内部缓冲区之一.在绘制时,一切都进入缓冲区.

>当你最终调用bs.show()时,bs将导致你刚绘制的缓冲区成为JFrame的当前缓冲区.它知道如何做到这一点,因为(见第1点)它知道它正在服务的JFrame.

这就是所有这一切.

通过对代码的评论……你应该稍微改变你的绘图程序.而不是这个:

try{
    g2 = (Graphics2D) bs.getDrawGraphics();
    drawWhatEver(g2);
} finally {
       g2.dispose();
}
bs.show();

你应该有一个像这样的循环:

do {
    try{
        g2 = (Graphics2D) bs.getDrawGraphics();
        drawWhatEver(g2);
    } finally {
           g2.dispose();
    }
    bs.show();
} while (bs.contentsLost());

这将防止丢失的缓冲帧,根据 the docs ,偶尔会发生这种情况.

翻译自:https://stackoverflow.com/questions/13590002/understand-bufferstrategy


以上所述就是小编给大家介绍的《java – 了解BufferStrategy》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

UCD火花集

UCD火花集

UCDChina / 人民邮电出版社 / 2009 / 25.00元

本书收集了UCDChina上线以来推出的13个话题,内容涵盖了产品设计的全部流程,按顺序集结到第一到第十三章中,讨论了如何研究用户、如何将用户需求应用到产品设计中、如何传达和协作。在第十四章,几位设计师分享了生活中的UE故事。第十五章,列举了一些实例和实践者的观点。本书适合有一定工作经验,从事产品设计、产品策划、交互设计、视觉设计、用户研究、前端开发、网站运营,以及所有与互联网有关的从业人员阅读。一起来看看 《UCD火花集》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具