gpt4 book ai didi

java - 了解 BufferStrategy

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:06:46 25 4
gpt4 key购买 nike

我是 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..
}
}

我不知道..我已经研究了很长时间了..而且一点运气都没有..我不知道..也许它就在那里,而且非常简单明了,我太笨了,看不出来..

感谢所有帮助..:)

最佳答案

这是它的工作原理:

  1. 当您调用 createBufferStrategy(2); 时,JFrame 构造一个 BufferStrategyBufferStrategy 知道它属于 JFrame 的特定实例。您正在检索它并将其存储在 bs 字段中。
  2. 当需要绘制您的东西时,您正在从 bs 中检索一个 Graphics2D。此 Graphics2D 对象绑定(bind)到 bs 拥有的内部缓冲区之一。在您绘制时,所有内容都会进入该缓冲区。
  3. 当您最终调用 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 , 偶尔会发生。

关于java - 了解 BufferStrategy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13590002/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com