gpt4 book ai didi

java - 我的重写绘制方法没有被调用

转载 作者:行者123 更新时间:2023-12-01 19:15:27 25 4
gpt4 key购买 nike

我有一个 JPanel 旨在充当我的游戏的 HUD,自然地,我已经重写了绘制方法来执行我自己的自定义显示,这确实被调用,但仅在调整大小或最大化、最小化框架时,而不是当我的游戏循环告诉它重新绘制()时。这对我来说似乎特别奇怪,因为我的另外两个面板被重新粉刷得很好。

这是我的 HUD 类:

package base;

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.BoxLayout;
import javax.swing.JPanel;

public class HUD extends JPanel {

private Shiphud[] shiphuds;

public HUD(Ship[] ships) {
shiphuds = new Shiphud[ships.length];
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
for (int i = 0; i < shiphuds.length; i++) {
shiphuds[i] = new Shiphud(ships[i]);
this.add(shiphuds[i]);
}
}
@Override
public void paint(Graphics g) {
for (int i = 0; i < shiphuds.length; i++) {
shiphuds[i].repaint();
}
}
public void run() {
repaint();
}
private class Shiphud extends JPanel {

private Ship ship;

public Shiphud(Ship ship) {
this.ship = ship;
}
@Override
public void paint(Graphics g) {
if (ship != null) {
g.setColor(Color.BLACK);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
int fullbar = (int) (this.getWidth() * 0.8);

g.setColor(Color.GREEN);
g.fillRoundRect(getWidth() / 10, getHeight() / 10,
(int) ((ship.energy / 1000) * fullbar), getHeight() / 6, 10, 10);

g.setColor(Color.blue);
g.fillRoundRect(getWidth() / 10, (int) (getHeight() * 0.4),
(int) ((ship.fuel / 1000) * fullbar), getHeight() / 6, 10, 10);

g.setColor(Color.YELLOW);
g.fillRoundRect(getWidth() / 10, (int) (getHeight() * 0.6),
(int) ((ship.ammo / 1000) * fullbar), getHeight() / 6, 10, 10);

g.setColor(Color.MAGENTA);
g.fillRoundRect(getWidth() / 10, (int) (getHeight() * 0.8),
(int) ((ship.special / 1000) * fullbar), getHeight() / 6, 10, 10);
System.out.println("here" + System.currentTimeMillis());
}
}
}
}

它与我的其他两个面板一起在我的游戏类更新中被调用

public void update() {
...
display.run();
display2.run();
hud.run();
}

由我的 JFrame 调用

public void runFrame() {
Thread thread = new Thread() {
@Override
public void run() {
gameLoop();
}
};
thread.start();
}
public void gameLoop() {
while (true) {
long beginTime = System.nanoTime();
game.update();
long timeTaken = System.nanoTime() - beginTime;
long timeLeft = (UPDATE_PERIOD - timeTaken) / 1000000; // in milliseconds
if (timeLeft < 10) {
timeLeft = 10; // set a minimum
}
try {
// Provides the necessary delay and also yields control so that other thread can do work.
Thread.sleep(timeLeft);
} catch (InterruptedException ex) {
}
}
}

我已经尝试解决这个问题很长时间了,但我就是不明白,任何帮助将不胜感激

最佳答案

不要重写 Swing 中的 paint 方法。

改为覆盖paintComponent

然后您不必为子组件调用 paintrepaint - 这将自动完成。

关于java - 我的重写绘制方法没有被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6818443/

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