gpt4 book ai didi

java - 运行此代码时系统卡住

转载 作者:太空宇宙 更新时间:2023-11-04 04:04:26 25 4
gpt4 key购买 nike

我正在 YouTube 上关注 Java 游戏编程系列,一切进展顺利,直到我们向程序添加一些代码。该程序的代码是:

package com.fagyapong.rain;

import javax.swing.*;
import java.awt.*;
import java.awt.image.*;

public class Game extends Canvas implements Runnable{
private static final long serialVersionUID = -247215114548172830L;

public static int width = 300;
public static int height = width / 16 * 9;
public static int scale = 3;

private JFrame frame;
public Thread thread;
private boolean running = false;

public Game() {

// Setup Game window
Dimension size = new Dimension(width * scale, height * scale);
setPreferredSize(size);

frame = new JFrame();
}

public synchronized void start() {
running = true;
thread = new Thread(this, "Display");
thread.start();
}

public synchronized void stop() {

running = false;
try {
thread.join();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}

public void run() {

while (running) {
update();
render();
}
}

public void update() {

}

public void render() {

// Get the canvas' BufferStragy object
BufferStrategy bs = getBufferStrategy();

if (bs == null) {
createBufferStrategy(3);
return;
}

Graphics g = bs.getDrawGraphics();

g.setColor(Color.GRAY);
g.fillRect(0, 0, getWidth(), getHeight());
g.dispose();
bs.show();
}

public static void main(String[] args) {

Game game = new Game();
game.frame.setResizable(false);
game.frame.setTitle("Rain");
game.frame.add(game);
game.frame.pack();
game.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
game.frame.setLocationRelativeTo(null);
game.frame.setVisible(true);

game.start();
}
}

下面是导致系统死机的代码(上面的代码已被注释掉)

Graphics g = bs.getDrawGraphics();

g.setColor(Color.GRAY);
g.fillRect(0, 0, getWidth(), getHeight());
g.dispose();
bs.show();

最佳答案

好吧,我稍微解决了这个问题。我也有同样的问题。对我来说问题是三重缓冲。相反,将代码设置为:

createBufferStrategy(2);

这样就只是双缓冲了。我没有一台出色的计算机,所以我必须将其设置为 1 而不是 2。此时,我的猜测是它根本没有缓冲。这就是我让它工作的方法。

关于java - 运行此代码时系统卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21805787/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com