gpt4 book ai didi

java - setColor Java 不工作

转载 作者:行者123 更新时间:2023-12-01 09:47:37 25 4
gpt4 key购买 nike

我正在遵循一个简单游戏引擎的教程,由于某种原因,当我尝试填充矩形时,setColor 不起作用。我只是得到一个空白的白屏。我看过其他类似的帖子,但似乎没有一个对我有帮助。这是代码:

package com.binaryscythe.SA.main;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;

/**
* @author 4nd3r
*
*/
public class Game extends Canvas implements Runnable {
private static final long serialVersionUID = -3472639816592189040L;

public static final int WIDTH = 1920, HEIGHT = WIDTH / 16 * 9;
private Thread thread;
private boolean running = false;

private Handler handler;

public Game() {
new Window(WIDTH, HEIGHT, "Senum's Adventure", this);
handler = new Handler();
}

public synchronized void start() {
thread = new Thread(this);
thread.start();
}

public synchronized void stop() {
try {

} catch(Exception e) {
e.printStackTrace();
}
}

public void run() {
long lastTime = System.nanoTime();
double amountOfTicks = 60.0;
double ns = 100000000 / amountOfTicks;
double delta = 0;
long timer = System.currentTimeMillis();
int frames = 0;
while (running) {
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
while(delta >= 1) {
tick();
delta--;
}
if (running)
render();
frames++;

if (System.currentTimeMillis() - timer > 1000) {
timer += 1000;
System.out.println("FPS: " + frames);
frames = 0;
}
}
stop();
}

private void tick() {
handler.tick();
}

private void render() {
BufferStrategy bs = this.getBufferStrategy();
if(bs == null) {
this.createBufferStrategy(3);
return;
}

Graphics g = bs.getDrawGraphics();

g.setColor(Color.black);
g.fillRect(0, 0, WIDTH, HEIGHT);

handler.render(g);

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

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

最佳答案

根据eldo的建议,

As far as I can see, you never set your running variable true. Your frame shows up but your game-loop never actually reach your render method. Try running = true; in your start method.

请检查running boolean 变量。如果是这种情况,请将他的答案标记为已接受。

否则,您也可以尝试以下代码片段: 通过 paint 方法并将 Graphics 转换为 Graphics2D

@Override
public void paint (Graphics g) {
Graphics2D g2 = (Graphics2D) g;

g2.setColor(Color.blue);
g2.fillRect(50, 50, 300, 300);

}

关于java - setColor Java 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37859011/

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