gpt4 book ai didi

java - JFrame 屏幕闪烁白光和黑光

转载 作者:行者123 更新时间:2023-12-02 13:41:14 24 4
gpt4 key购买 nike

我有一个问题,我的 JFrame 不断闪烁白色和黑色,但我只将颜色设置为黑色。我认为这与 while (running) {} 位有关。

它永远变成白色和黑色,直到我关闭它。我真的不知道发生了什么事..我才刚刚开始使用 JFrame,所以我确定我刚刚输入了一些错误的代码。

public class Game extends Canvas implements Runnable {

private static final long serialVersionUID = 1L;

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

private Thread thread;

private JFrame frame;

public Game() {
Dimension window = new Dimension(width * scale, height * scale);
setPreferredSize(window);
frame = new JFrame();
}

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

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

public void run() {
while (running) {
render();
}
}

public void update() {

}

public void render() {
BufferStrategy buffer = getBufferStrategy();

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

Graphics g = buffer.getDrawGraphics();

g.setColor(Color.BLACK);
g.drawRect(0, 0, getWidth(), getHeight());

g.dispose();
buffer.show();
}

public static void main(String[] args) {
Game game = new Game();

game.frame.setResizable(false);
game.frame.setTitle("Game");
game.frame.add(game);
game.frame.pack();
game.frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
game.frame.setLocationRelativeTo(null);
game.frame.setVisible(true);

game.start();
}
}

最佳答案

我自己解决了...我使用了方法drawRect()并且我阅读了文档页面,它说它只绘制了矩形的轮廓..所以我只是做了drawRect()我还将缓冲区更改为 2。

抱歉浪费了您的时间。

关于java - JFrame 屏幕闪烁白光和黑光,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42735232/

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