0

I'm creating a game in java using Graphics2D and the Canvas class.

When I run the program a JFrame appears on my first monitor and there are no problems. However, when I drag the JFrame onto my second monitor it turns gray and will stop rendering anything, then when I drag it back onto my first monitor the program continues rendering..

My game loop calls a draw() method in my Screen class that extends Canvas, This is the draw method.

public void draw(){
    BufferStrategy bs = getBufferStrategy();
    if(bs == null){
        createBufferStrategy(2);
        bs = getBufferStrategy();
        g = (Graphics2D) bs.getDrawGraphics();
    }

    g.setColor(Color.BLACK);
    g.fillRect(0, 0, getWidth(), getHeight());

    g.setColor(Color.WHITE);
    g.drawString("Hello, this works", 300, 300);

    g.drawImage(ImageLoader.test[0][0], 100, 100, null);

    bs.show();
}
Shaun Wild
  • 1,237
  • 3
  • 17
  • 34
  • http://stackoverflow.com/questions/4627553/show-jframe-in-a-specific-screen-in-dual-monitor-configuration , hope this helps :) – Joe Tannoury Mar 30 '16 at 20:05
  • Nope that doesn't help. The code in that puts the JFrame onto my other screen but if I drag it across screens it breaks again. I want to be able to drag my Jframe between monitors without it breaking. – Shaun Wild Mar 30 '16 at 20:10
  • if you put sort-of this type of script in a loop or event I believe it would work – Joe Tannoury Mar 30 '16 at 20:32

1 Answers1

1

Do not keep a reference to a Graphics (or Graphics2D) object beyond the scope of your method.

Move g = (Graphics2D) bs.getDrawGraphics(); outside of your if-block. You need to obtain a new Graphics each time you draw.

You also need to dispose of the Graphics as soon as you're done drawing on it.

Using a BufferStrategy is a little complicated. I recommend you look at the example code in the BufferStrategy documentation. In particular, you need to surround your rendering with loops that check the values returned by the BufferStrategy's contentsRestored() and contentsLost() methods.

VGR
  • 40,506
  • 4
  • 48
  • 63
  • Thank you, this has also fixed another problem I have where the game seems to break everytime it's resized. – Shaun Wild Apr 04 '16 at 12:25