Search code examples
javacanvasawtdoublebufferedcustom-painting

Can't close window after adding canvas in Java


public class Screen extends Canvas{
    private BufferedImage image;
    private int height = Toolkit.getDefaultToolkit().getScreenSize().height-37;
    private int width = Toolkit.getDefaultToolkit().getScreenSize().width;
    private boolean running = false;
    public Screen(){
        setSize(width, height);
        try {image = ImageIO.read(new File("success.jpg"));}
        catch (Exception e) {Utilities.showErrorMessage(this, e);}
        setVisible(true);
        running = true;
    }


    public void paint(Graphics g){
        while(running){
            BufferStrategy bs = getBufferStrategy();
            if(bs == null){
                createBufferStrategy(3);
                return;
            }
            g = bs.getDrawGraphics();
            g.drawImage(image,0,0,width,height, null);
            g.dispose();
            bs.show();
        }
    }
}

This is a preliminary display screen within my Game JFrame that is added upon starting the game. Code runs fine but after adding the canvas, I can't seem to exit the program through normal means. (exit button) It worked fine in the menu and yes, I did set the defaultCloseOperation in the JFrame. Any ideas on why this might be?


Solution

  • This...

    public void paint(Graphics g){
        while(running){
            BufferStrategy bs = getBufferStrategy();
            if(bs == null){
                createBufferStrategy(3);
                return;
            }
            g = bs.getDrawGraphics();
            g.drawImage(image,0,0,width,height, null);
            g.dispose();
            bs.show();
        }
    }
    

    Is not how custom painting should be done. Basically what this is blocking the Event Queue, which means, apart from been able to respond to new paint events, it's preventing it from processing any new events.

    In this case, it would be better to create a separate Thread and perform this action within that Thread's run method.

    Have a look at Painting in AWT and Swing for more details