canvas with BufferStrategy in Fullscreen problem

Howdy all,

I’m trying to draw on a canvas object using BufferStrategy, but I’m having some problems.

I first tried to set my BufferStrategy in the constructor of the canvas i was using:


public class WorldView extends Canvas
{  private BufferStrategy strat

   public WorldView()
   {  super();

          this.layoutView();
          this.registerListeners();

          this.createBufferStrategy(2);
          this.strat = this.getBufferStrategy();
   }
}

However, when I ran my program i got this error:

java.lang.IllegalStateException: Component must have a valid peer

  at java.awt.Component$FlipBufferStrategy.createBuffers(Component.java:3039)

  at java.awt.Component$FlipBufferStrategy.<init>(Component.java:3014)

  at java.awt.Component.createBufferStrategy(Component.java:2923)

  at java.awt.Canvas.createBufferStrategy(Canvas.java:166)

  at java.awt.Component.createBufferStrategy(Component.java:2855)

  at java.awt.Canvas.createBufferStrategy(Canvas.java:141)

  at Dune2.View.WorldView.<init>(WorldView.java:60)

  at Dune2.View.TopLevelView.<init>(TopLevelView.java:37)

  at Dune2.Model.Start.main(Start.java:33)

I really didn’t know what to make of this. I found that exception type and its somthing like ‘the method is being called at an inappropriate time’. So, I decided to try to put the code for creating the bufferstrategy in my code for drawing the stuff on the screen:


private void drawGraphics()  {  
      if (!this.buffersSet)
      {  this.createBufferStrategy(2);
         this.strategy = this.getBufferStrategy();
         this.buffersSet = true;
      }
      Graphics g = this.strategy.getDrawGraphics();
      this.render(g);
      g.dispose();
      this.strategy.show();
}

This doesn’t work either. I don’t get an exception, but rather nothing draws and I don’t see anything but light gray where my game should be :\ The method ‘render(g)’ is just my method that draws all the units (ie. g.drawImage(----)).

Somthing else that I thought might be a problem was that in my render method, I’m converting the Graphics object g into a Graphics2D object (I need Graphics2D for AffineTransform) so that I could rotate the images I draw on the screen.

Could anyone help me out here?

Thanks,
Chisser98

you can’t create a strategy from an undispayable canvas (basically a canvas w/o a peer). it needs to be added to a realized parent first.

You should rearrange your code to create the strategy after the canvas is added to a visible (or pack()-ed in case of frame) container. Something in the lines of:

Frame f = new Frame();
f.pack(); // this will realize the frame (make it displayable)

WorldView wv = new WorldView();
f.add(wv);
wv.createBufferStrategy();