【问题标题】:White screen appearing in java when i use g.drawString当我使用 g.drawString 时出现在 java 中的白屏
【发布时间】:2017-08-09 00:02:14
【问题描述】:

所以我应该制作一个在 HUD 中有分数的游戏,但每当我使用代码时

g.drawString("Score: " + score, 15, 64);
//score is a variable

出现这样的白屏

HUD的完整代码是这样的

import java.awt.Color;
import java.awt.Graphics;

public class HUD {

public static int HEALTH = 800;

private static int gvalue = 255;

public int score = 0;
public int level = 1;

   public void tick(){
         HEALTH = MainGame.clamp(HEALTH, 0, 800);

         gvalue = MainGame.clamp(gvalue, 0, 255);
         gvalue = HEALTH/4;

         score++;
   }

public void render(Graphics g){
       g.setColor(Color.gray);
       g.fillRect(15, 15, 200, 30);
       g.setColor(new Color(70, gvalue, 0));
       g.fillRect(15, 15, (HEALTH / 4) , 30);
       g.setColor(Color.white);
       g.drawRect(15, 15, 100 * 2, 30);

       g.drawString("Score: " + score, 15, 64);
       //the line above though, when i remove it, it completely works
   }

  public int getScore() {
        return score;
    }

    public void setScore(int score) {
        this.score = score;
    }

    public int getLevel() {
        return level;
    }

    public void setLevel(int level) {
        this.level = level;
    }
    } 

P.S 我有对象、窗口、颜色等,但它们在其他类中。 P.P.S 当我删除上述行时,它工作正常。

【问题讨论】:

  • 您需要使用 .setBackground(Color.black); 来添加背景色;
  • 我有背景颜色、对象和东西,但它们在其他类中。

标签: java user-interface graphics awt


【解决方案1】:

我没有看到任何声明字体或字体颜色的内容...

g.setColor(Color.black);
Font font = new Font("Times New Roman", Font.BOLD, (int) Math.round(20 * scaleX));
g.setFont(font);
g.drawString("Score: " + score, 15, 64);

我希望这会有所帮助。

【讨论】:

  • 这个世界上有两种人,第一种:Font font = new Font("Times New Roman", Font.BOLD, 13)第二种:g.setFont(new Font("Times New Roman", Font.BOLD, 13))
【解决方案2】:

我知道这已经快 4 岁了,但我在 youtube 上遵循相同的教程并遇到了同样的问题。我也找到了一个解决方案,所以在这里发帖以防其他人偶然发现这个帖子:

在我的情况下,这是解决它的方法: 在 Game 类中(你有游戏循环和渲染/滴答方法),查看渲染方法。 就我而言,我必须将 createBufferStrategy() 中的数字从 2 更改为 3。 所以这段代码现在可以工作了:

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

我现在可以在 HUD 类中成功地 g.drawString

【讨论】:

    猜你喜欢
    • 2017-01-22
    • 1970-01-01
    • 1970-01-01
    • 2021-04-15
    • 1970-01-01
    • 2022-01-02
    • 2020-01-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多