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

这是我的 Game JFrame 中的一个初步显示屏幕,它是在开始游戏时添加的。代码运行良好,但添加画布后,我似乎无法通过正常方式退出程序。(退出按钮)它在菜单中运行良好,是的,我确实在 JFrame 中设置了 defaultCloseOperation。关于为什么会这样的任何想法?

4

1 回答 1

1

这个...

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

不是应该如何定制绘画。基本上这是阻塞事件队列的原因,这意味着除了能够响应新的绘制事件之外,它还会阻止它处理任何新事件。

在这种情况下,最好创建一个单独的Thread并在 thatThreadrun方法中执行此操作。

查看在 AWT 和 Swing 中的绘画以了解更多详细信息

于 2014-05-26T00:04:37.033 回答