13

私は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..
   }
  }

わからない..私はこれを長い間研究してきました..そしてまったく運がありません..私は知りません..多分それはすべてそこにあります、そしてそれは本当に明確で単純です、そして私は' m愚かすぎて、それを見ることができません。

すべての助けをありがとう..:)

4

1 に答える 1

27

仕組みは次のとおりです。

  1. を呼び出すと、をJFrame構成します。は、それがの特定のインスタンスに属していることを知っています。あなたはそれを取得してフィールドに保存しています。BufferStrategycreateBufferStrategy(2);BufferStrategyJFramebs
  2. 自分のものを描くときになると、Graphics2Dからを取得していbsます。このGraphics2Dオブジェクトは、が所有する内部バッファの1つに関連付けられてい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());

これにより、バッファフレームが失われるのを防ぐことができます。これは、ドキュメントによると、ときどき発生する可能性があります。

于 2012-11-27T17:56:00.460 に答える