有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

缓冲策略Java缓冲策略有时不能正确绘制

我用Java创建了一个使用缓冲策略的游戏。但有时我只得到一个白色的框架或白色的边框。这种情况大约每五次发生一次。我搜索了很多,但我真的不知道我做错了什么。代码经过编译,没有打印出任何错误

如果失败,框架看起来像这样:

white border

completely white frame

以下是代码(仅适用于相关部分):

private BufferStrategy bs;
public Testclass(){
    setResizable(false);
    setSize(1000,600);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setIgnoreRepaint(true);
    setVisible(true);
    createBufferStrategy(2);
    bs = getBufferStrategy();
}

protected void paint() {
    do {
        Graphics2D g=null;
        try {
            g = (Graphics2D) bs.getDrawGraphics();
            g.setColor(Color.CYAN);
            g.fillRect(0, 0, this.getWidth(), this.getHeight());
        } finally {
            g.dispose();
        }
        bs.show();
    } while (bs.contentsLost());
}

public static void main(String[] args) {
    Testclass window = new Testclass();
    window.paint();
}

共 (1) 个答案

  1. # 1 楼答案

    实际上我找到了一个更好的方法来尝试:

       boolean BufferStrategyRunning = true;
    
        while(BufferStrategyRunning == true) {
    
            BufferStrategy BS = GUIFrame.getBufferStrategy();
    
            if(BS == null) {
            GUIFrame.createBufferStrategy(3);
            continue;
            }
    
            Graphics g = BS.getDrawGraphics();
    
            g.drawImage(CurrentScreen.BackgroundImage, 0, 0, null);
            g.dispose();
            BS.show();
    
    
        }