gpt4 book ai didi

java - 无法在java中绘制形状

转载 作者:行者123 更新时间:2023-12-02 07:32:59 24 4
gpt4 key购买 nike

我非常确定这段代码应该在屏幕上的单词文本旁边绘制一个椭圆形。然而,这个词全部出现,屏幕的其余部分是黑色的。这似乎发生在任何原始形状上。我想我对java相当了解,但图形化的东西对我来说真的很困惑。我对此无能为力,任何帮助将不胜感激。

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

public class Game extends JPanel implements Runnable {
int W = 4;
int H = 3;
int windowSize = 300;
boolean running;
static boolean drawHitBoxes = true;
int FPSLimit = 30;

private Thread thread;
private BufferedImage buffer;
private Graphics2D g;

public Game() {
super();
setPreferredSize(new Dimension(W * windowSize, H * windowSize));
setFocusable(true);
requestFocus();
}

public void addNotify() {
super.addNotify();
if (thread == null) {
thread = new Thread(this);
thread.start();
}
}

public void run() {
running = true;

buffer = new BufferedImage(W * windowSize, H * windowSize,
BufferedImage.TYPE_INT_RGB);
g = (Graphics2D) buffer.getGraphics();

// citList.add(new Citizen(200, 200, "Joe"));

long startTime;
long waitTime;

long frameTime = 1000 / FPSLimit; // /How long one frame should take
long currentFrameTime;

while (running) {
startTime = System.nanoTime(); // record when loop starts

gameUpdate();
gameRender();
gameDraw();

// Calculate how long the current frame took
currentFrameTime = (System.nanoTime() - startTime) / 1000000;
waitTime = frameTime - currentFrameTime;

try {
Thread.sleep(waitTime);
} catch (Exception e) {
} // Sleep for the remaining time
}
}

private void gameUpdate() {
// for(Citizen i:citList){i.update();} //Update citizens
}

private void gameRender() {
g.setColor(Color.WHITE);
g.drawOval(100, 100, W - 100, H - 100);
g.setColor(Color.WHITE);
g.drawString("Text.", 100, 100);
System.out.println("Drawing white box.");

// for(Citizen i:citList){i.draw(g);} //Draw citizens
}

private void gameDraw() {
Graphics gMain = this.getGraphics();
gMain.drawImage(buffer, 0, 0, null);
}
}

最佳答案

g.drawOval(100, 100, W-100, H-100);

W 为 4,H 为 3,因此由于 W-100 为 -96,H-100 为 -97,因此第三个和第四个参数为负数,这对于 Graphics#drawOval(...) 方法没有意义,因为椭圆形的宽度和高度怎么可能是负数。解决方案:确保在调用此方法时仅使用有意义的正参数。也许您想要的是:

 // but you'll also want to avoid magic numbers such as 100 & 200 as well
g.drawOval(100, 100, W * windowSize - 200, H * windowSize - 200);

顺便说一句,我自己更喜欢使用被动图形,在 PaintComponent 中绘图,并且每当我看到具有 Graphics 或 Graphics2D 实例字段的 Swing 代码时我都会感到害怕。此外,您的代码看起来不遵守 Swing 线程规则,因为它似乎从 Swing 事件线程发出 Swing 调用。

关于java - 无法在java中绘制形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31925970/

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