Java - Paint、JFrame 和背景

发布于 2024-09-24 14:43:33 字数 426 浏览 2 评论 0原文

我正在尝试为我的游戏绘制欢迎屏幕,但仅限于游戏加载时。我不想在游戏过程中每次都重新绘制。

所以我这样做了(其中 isStart 被实例化为 true):

public myClass(String name){
    setSize(800, 800);
    setVisible(true);
    setResizable(false);
    runGame()
}

public void paint(Graphics g) {
    if(nowStarting)
        g.drawImage(WelcomeGameScreen, 0, 0, null);
    isStart = false;
}

问题是图像会弹出一秒钟然后消失?奇怪的是,当我省略 if 语句/isStart 条件时它会起作用。这有什么问题吗?

I'm trying to paint a Welcome Screen for my game, but only when the game loads. I don't want it to repaint everytime during the game.

So I did this (where isStart is instantiated as true):

public myClass(String name){
    setSize(800, 800);
    setVisible(true);
    setResizable(false);
    runGame()
}

public void paint(Graphics g) {
    if(nowStarting)
        g.drawImage(WelcomeGameScreen, 0, 0, null);
    isStart = false;
}

The problem is that the image will pop up for a second and then disappear? Oddly, it works when I leave out the if statement/isStart condition. What's wrong with this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

梦醒灬来后我 2024-10-01 14:43:33

我猜测您没有逐字复制代码,并且上面的代码中有错误。如果你的代码是我认为的那样......

public void paint(Graphics g) {
    if(isStart)
        g.drawImage(WelcomeGameScreen, 0, 0, null);
    isStart = false;
}

那么在开始时它会绘制你的启动屏幕。但是,因为您随后将 isStart 设置为 false,所以下次调用 Paint 时,将不再绘制图像。每当操作系统告诉屏幕需要刷新时(以及当您强制重新绘制时),都会调用paint方法。

解决这个问题的方法是,当游戏完成加载时,在应用程序中将 isStart 设置为 false,然后调用 repaint。

I am guessing that you have not copied verbatim the code, and there is an error in your code above. If your code is what I think it is...

public void paint(Graphics g) {
    if(isStart)
        g.drawImage(WelcomeGameScreen, 0, 0, null);
    isStart = false;
}

Then at start it will draw your splash screen. But, because you are then setting isStart to false, the next time paint is called, the image will no longer be drawn. The paint method is called whenever the OS tells the screen that it needs to be refreshed (and when you force it with repaint).

The way you can get around this, is to set isStart to false in your application when the game has finished loading, and then call repaint.

一页 2024-10-01 14:43:33

我猜一旦绘制面板,您的 newStarting 布尔值就会更改为 false

I guess your newStarting boolean gets changed to false as soon as the panel is painted.

若相惜即相离 2024-10-01 14:43:33

它立即消失的原因是 Swing 框架触发的重绘。另外,您已经在重写的 Paint() 方法中编写了欢迎屏幕的代码。

有关如何触发启动的详细说明,请参阅链接窗户。
Java 1.6 中还有一个 SplashScreen

The reason it gets disappeared immediately is because of the repaints that are triggered by the Swing framework. Plus you have written the code for Welcome screen inside the overridden paint() method.

Refer this link for a detailed explanation of how to fire a splash window.
You also have a SplashScreen class in Java 1.6

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文