Search code examples
javaawtgame-enginegraphics2d

Java game won't render on second monitor


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();
}

Solution

  • 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.